头文件
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
Server端
1.创建socket通信
struct sockaddr_in sin;//定义套接字
int sock;//文件描述符
if((sock = socket(AF_INET,SOCK_DGRAM,0))==-1){
perror("socket");
exit(1);
}
memset(&sin,0,sizeof(sin));//重置【刷新】套接字sin然后赋值
sin.sin_family=AF_INET;//协议
sin.sin_port=htons(5001);//绑定端口
sin.sin_addr.s_addr=htonl(INADDR_ANY);// 地址0x0000 任意网卡的ip都能用
2.绑定接口bind
if(bind(sock,(struct sockaddr*)&sin,sizeof(sin))==-1){
perror("bind");
exit(1);
}
3.接收字符
char buff[BUFSIZ];//接收字符串
socklen_t sock_len = sizeof(sin);
while (1) {
memset(buff,0,sizeof(buff));//重置传输buff
if(recvfrom(sock,buff,BUFSIZ,0,(struct sockaddr *)&sin,&sock_len)<0){
perror("recvfrom");
break;
}
printf("massage:%s",buff);
}
4.关闭套接字
close(sock);
Client端
1.创建socket通信
if((sock = socket(AF_INET,SOCK_DGRAM,0))==-1){
perror("socket");
exit(1);
}
memset(&s,0,sizeof(s));//重置套接字s
sin.sin_family=AF_INET;//协议族
sin.sin_port=htons(5001);//绑定端口
if(inet_pton(AF_INET,"192.168.0.0",(void*)& sin.sin_addr.s_addr)!=1){
perror("inet_pton");
exit(1);
}//服务器端ip
2.发送数据
char buff[BUFSIZ];
socklen_t addrlen = sizeof(sin);
while(1){
printf("please input:");
memset(&buff,0,sizeof(buff));//重置传输buff
if(sendto(sock,buff,strlen(buff),0,(struct sockaddr*)&s,addrlen)<0){
perror("sendto");
exit(1);
}
}
3.关闭套接字
close(sock);