UDP通讯试手
【摘要】 server.c#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <stdio.h>#define PORT 16110 /*浣跨敤鐨刾ort*/int main(){ int...
server.c
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #define PORT 16110 /*浣跨敤鐨刾ort*/ int main(){ int sockfd,len; struct sockaddr_in addr; int addr_len = sizeof(struct sockaddr_in); char buffer[256]; /*寤虹珛socket*/ if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0){ perror ("socket"); exit(1); } /*濉啓sockaddr_in 缁撴瀯*/ bzero ( &addr, sizeof(addr) ); addr.sin_family=AF_INET; addr.sin_port=htons(PORT); addr.sin_addr.s_addr=htonl(INADDR_ANY) ; if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr))<0){ perror("connect"); exit(1); } while(1){ bzero(buffer,sizeof(buffer)); len = recvfrom(sockfd,buffer,sizeof(buffer), 0 , (struct sockaddr *)&addr ,&addr_len); /*鏄剧ずclient绔殑缃戠粶鍦板潃*/ printf("receive from %s,size:%d\n", inet_ntoa( addr.sin_addr), len); /*灏嗗瓧涓茶繑鍥炵粰client绔?*/ sendto(sockfd,buffer,len,0,(struct sockaddr *)&addr,addr_len); } } client.c #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #define PORT 16110 #define SERVER_IP "127.0.0.1" int main() { int s,len; struct sockaddr_in addr; int addr_len =sizeof(struct sockaddr_in); char buffer[256]; /* 寤虹珛socket*/ if((s = socket(AF_INET,SOCK_DGRAM,0))<0){ perror("socket"); exit(1); } /* 濉啓sockaddr_in*/ bzero(&addr,sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr(SERVER_IP); while(1){ bzero(buffer,sizeof(buffer)); printf("please input some message\n"); /* 浠庢爣鍑嗚緭鍏ヨ澶囧彇寰楀瓧绗︿覆*/ len =read(STDIN_FILENO,buffer,sizeof(buffer)); /* 灏嗗瓧绗︿覆浼犻€佺粰server绔?/ sendto(s,buffer,len,0,(struct sockaddr *)&addr,addr_len); /* 鎺ユ敹server绔繑鍥炵殑瀛楃涓?/ len = recvfrom(s,buffer,sizeof(buffer),0,(struct sockaddr *)&addr,&addr_len); printf("receive: %s",buffer); } }
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)