UDP网络程序设计
课程索引
编程模型函数化
发送数据
Sendto
接收数据
Recvfrom
udp_server.c
1 #include <stdio.h> 2 #include <string.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 5 6 #define PORT 8888 7 #define MSG_SIZE 128 8 9 int main() 10 { 11 int sockfd; 12 struct sockaddr_in server_addr; 13 struct sockaddr_in client_addr; 14 char buffer[MSG_SIZE]; 15 int addrlen; 16 int n; 17 18 //创建套接字 19 sockfd = socket(AF_INET,SOCK_DGRAM,0); 20 21 //绑定地址 22 bzero(&server_addr,sizeof(struct sockaddr_in)); 23 server_addr.sin_family = AF_INET; 24 server_addr.sin_port = htons(PORT); 25 server_addr.sin_addr.s_addr = htonl(INADDR_ANY); 26 27 bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr)); 28 29 //接收数据 30 while(1) 31 { 32 addrlen = sizeof(struct sockaddr); 33 bzero(buffer,sizeof(buffer)); 34 n = recvfrom(sockfd,buffer,MSGZ-SIZE,0,(struct sockaddr *)(&client_addr),&addrlen); 35 buffer[n]=0;//加上结束符 36 printf("Server received: %s\n",buffer); 37 } 38 39 //结束连接 40 close(sockfd); 41 42 return 0; 43 }
udp_client.c
1 #include <stdio.h> 2 #include <string.h> 3 #include <sys/socket.h> 4 #include <netinet/in.h> 5 6 #define BUF_SIZE 128 7 #define PORT 8888 8 9 int main(int argc, char **argv) 10 { 11 int sockfd; 12 char buffer[BUF_SIZE]; 13 struct sockaddr_in server_addr; 14 15 if(argc != 2) 16 { 17 printf("Usage: %s server_ip\n",argv[0]); 18 exit(1); 19 } 20 21 //创建套接字 22 sockfd = socket(AF_INET,SOCK_DGRAM,0); 23 24 //初始化服务器地址 25 bzero(&server_addr,sizeof(struct sockaddr_in)); 26 server_addr.sin_family = AF_INET; 27 server_addr.sin_port = htons(PORT); 28 inet_aton(argv[1],&server_addr.sin_addr) 29 30 //发送数据 31 while(1) 32 { 33 printf("Please input char:\n"); 34 fgets(buffer,BUF_SIZE,stdin); 35 sendto(sockfd,buffer,strlen(buffer),0,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr)); 36 bzero(buffer,BUF_SIZE); 37 } 38 39 close(sockfd); 40 41 return 0; 42 }
原文:http://www.cnblogs.com/love-linux/p/5208485.html