unix 网络编程udp简单例程
server.c #include /* See NOTES */ #include #include #include #include #include #include #include int main(int argc, char** argv) { int ret; int len = sizeof(struct sockaddr); //创建socket int sockfd = socket(AF_INET, SOCK_DGRAM,0); if(sockfd == -1) { perror("socket\n"); exit(1); } //将addr地址与socket绑定在一起 //初始化地址 struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(4444); addr.sin_addr.s_addr = INADDR_ANY; memset(addr.sin_zero,8,0); //进行绑定 ret = bind(sockfd, (struct sockaddr*)&addr, len); if(ret == -1) { perror("bind\n"); exit(1); } //接收数据 struct sockaddr_in addr_client; while(1) { char buf[100]; memset(buf,100,0); socklen_t length = sizeof(struct sockaddr); fputs("等待数据。。。。\n",stdout); ssize_t recnum = recvfrom(sockfd, buf, 100,MSG_WAITALL, (struct sockaddr*)&addr_client,&length); if(recnum<0) { perror("recvfrom\n"); exit(1); } printf("received(%d): %s\n",recnum,buf); if(strcmp(buf,"stop") == 0) { break; } } close(sockfd); fputs("退出成功!!\n",stdout); return 0; } ----------------------------client.c #include /* See NOTES */ #include #include #include #include #include #include #include int main(int argc, char** argv) { int len = sizeof(struct sockaddr); //创建socket int sockfd = socket(AF_INET, SOCK_DGRAM,0); if(sockfd == -1) { perror("socket\n"); exit(1); } //将addr地址与socket绑定在一起 //初始化地址 struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(4444); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(addr.sin_zero,8,0); while(1) { char buf[100]; memset(buf,100,0); fputs("请输入内容:\n",stdout); //存在scanf字符串空格问题 scanf("%s",buf); fputs("确认发送内容为:\n",stdout); fputs(buf,stdout); printf("\n"); sendto(sockfd, buf, 100, 0, (struct sockaddr*)&addr, len); fputs("确认发送完成\n",stdout); } return 0; } ----------------------------makefile .PHONY: all clean all:server client server:server.c gcc -o server server.c -Wall client:client.c gcc -o client client.c -Wall clean: rm -f *.o client server *~
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~