(一)UDP服务器编程的端一般步骤是:
1、用函数socket()创建socket,第二个参数为SOCK_DGRAM
2、用函数bind()绑定IP地址、端口信息
3、用函数recvfrom()接收数据
4、关闭网络连接;
UDP客户端编程的一般步骤是:
1、创建一个socket,用函数socket(),第二个参数为SOCK_DGRAM
2、使用connect()来建立与服务程序的连接
3.发送数据,用函数send()
4.关闭网络连接
(二)UDP通信服务端程序为:
# include <stdio.h> # include <sys/socket.h> # include <arpa/inet.h> # include <string.h> # define MAXSIZE 256 int main(void) { int sockfd; struct sockaddr_in servaddr,clientaddr; int n,addrlen=sizeof(struct sockaddr_in); char buf[MAXSIZE]; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(5555); servaddr.sin_addr.s_addr=INADDR_ANY; if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1) { perror("listen"); return -1; } if(bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))==-1) { perror("bind"); return -1; } n=recvfrom(sockfd,buf,MAXSIZE,0,(struct sockaddr *)&clientaddr,(socklen_t *)&addrlen); if(n==-1) { perror("recvfrom"); return -1; } buf[n]='\0'; printf("%s \n",buf); close(sockfd); return 0; }
客户端程序为:
# include <stdio.h> # include <sys/socket.h> # include <string.h> # include <arpa/inet.h> # define MAXSIZE 256 int main(void) { int sockfd,n; char buf[MAXSIZE],sbuf[MAXSIZE]="i am child"; struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(5555); inet_pton(AF_INET,"127.0.0.1",&servaddr.sin_addr); if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1) { perror("socket"); return -1; } printf("%d \n",sockfd); if(connect(sockfd,(struct sockaddr *)&servaddr,(socklen_t)sizeof(servaddr))<0) { perror("connect"); return -1; } printf("conneted \n"); //memset(sbuf,0,20); if(send(sockfd,sbuf,strlen(sbuf)+1,0)<0) { perror("send"); return -1; } printf(" sended"); close(sockfd); return 0; }