面向无连接的SOCKET通信_幸运啤酒盖-ChinaUnix博客

网友投稿 650 2022-09-23

面向无连接的SOCKET通信_幸运啤酒盖-ChinaUnix博客

面向无连接的SOCKET通信_幸运啤酒盖-ChinaUnix博客

客户端:

#include #include #include #include #include #include #include #include #include #define REMOTEPORT 4567#define REMOTEIP "127.0.0.1"int main(int argc,char *argv[]){int s,len;struct sockaddr_in addr;int addr_len;char msg[256];int i=0;if((s=socket(AF_INET,SOCK_DGRAM,0))<0){perror("error");exit(1);}else{printf("socket created.\n");printf("socket id : %d\n",s);printf("remote ip :%s\n",REMOTEIP);printf("remote port :%d\n",REMOTEPORT);}addr_len=sizeof(struct sockaddr_in);bzero(addr,sizeof(addr));addr.sin_family=AF_INET;addr.sin_port=htons(REMOTEPORT);addr.sin_addr.s_addr=inet_addr(REMOTEIP);while(1){bzero(msg,sizeof(msg));len=read(STDIN_FILENO,msg,sizeof(msg));sendto(s,msg,len,0,addr,addr_len);printf("\nInput message : %s",msg);len=recvfrom(s,msg,sizeof(msg),0,addr,addr_len);printf("%d :",i);i ;printf("Received message: %s \n",msg);}}

服务器端:

#include #include #include #include #include #include #define LOCALPORT 4567int main(int argc,char *argv[]){int mysock,len;struct sockaddr_in addr;int addr_len;int i=0;char msg[256];if((mysock=socket(AF_INET,SOCK_DGRAM,0))<0){perror("error:");exit(1);}else{printf("socket created.\n");printf("socket id : %d\n",mysock);}addr_len=sizeof(struct sockaddr_in);addr.sin_family=AF_INET;addr.sin_port=htons(LOCALPORT);addr.sin_addr.s_addr=htonl(INADDR_ANY);if(bind(mysock,addr,sizeof(addr))<0){perror("connect:");exit(1);}else{printf("bind OK\n");printf("local port :%d\n",LOCALPORT);}while(1){bzero(msg,sizeof(msg));len=recvfrom(mysock,msg,sizeof(msg),0,addr,addr_len);printf("%d:",i);i ;printf("message from:%s\n",inet_ntoa(addr.sin_addr));printf("message length:%d\n",len);printf("message :%s\n",msg);sendto(mysock,msg,len,0,addr,addr_len);}}

测试结果:实现本机上UDP通信,可以通过修改REMOTEIP,REMOTEPORT来实现自己想要的结果。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:主引导扇区MBR的解析_Bean_lee-ChinaUnix博客
下一篇:Python 的高级特征你知多少?来对比看看(python培训)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~