Linux----网络编程(UDP网络通信服务器客户端编程流程)

1、服务器ser.c

  1 #include <string.h>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4 #include <unistd.h>
  5 #include <assert.h>
  6 #include <sys/socket.h>
  7 #include <netinet/in.h>
  8 #include <arpa/inet.h>
  9 
 10 //服务器与客户端UDP
 11 int main()
 12 {
 13     int sockfd = socket(AF_INET, SOCK_DGRAM, 0);//套接字
 14     assert(sockfd != -1);
 15 
 16     struct sockaddr_in saddr, caddr;
 17     memset(&saddr,0, sizeof(saddr));
 18     saddr.sin_family = AF_INET;
 19     saddr.sin_port = htons(6001);
 20     saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
 21 
 22     int res = bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr));
 23     assert(res != -1);
 24 
 25     while(1)
 26     {
 27         int len = sizeof(caddr);
 28         char buff[128] = {0};
 29         recvfrom(sockfd,buff, 1,0,(struct sockaddr*)&caddr, &len);//127->1
 30         printf("ip=%s,port=%d,buff=%s\n",inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port),buff);
 31 
 32         sendto(sockfd,"ok", 2, 0,(struct sockaddr*) &caddr,sizeof(caddr));
 33     }
 34 }

2、客户端cli.c

  1 #include <string.h>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4 #include <unistd.h>
  5 #include <assert.h>
  6 #include <sys/socket.h>
  7 #include <netinet/in.h>
  8 #include <arpa/inet.h>
  9 
 10 //服务器与客户端UDP
 11 int main()
 12 {
 13     int sockfd = socket(AF_INET, SOCK_DGRAM, 0);//套接字
 14     assert(sockfd != -1);
 15 
 16     struct sockaddr_in saddr, caddr;
 17     memset(&saddr,0, sizeof(saddr));
 18     saddr.sin_family = AF_INET;
 19     saddr.sin_port = htons(6001);
 20     saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
 21 
 22     while(1)
 23     {
 24         char buff[128] = {0};
 25         printf("input:\n");
 26 
 27         fgets(buff,128,stdin);
 28         if(strncmp(buff,"end",3) == 0)
 29         {
 30             break;
 31             }
 32 
 33         sendto(sockfd,buff,strlen(buff),0,(struct sockaddr*)&saddr, sizeof(saddr));
 34         memset(buff,0,128);
 35         int len = sizeof(caddr);
 36         recvfrom(sockfd,buff,127,0,(struct sockaddr*)&caddr, &len);
 37         printf("buff=%s\n",buff);
 38     }
 39  close(sockfd);
 40 }

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值