Linux--UDP通信简单程序

服务器程序:使用recvfrom函数阻塞接收信息。并将信息用sendto函数发回去

客户端程序:使用sendto函数,发送数据给客户端。然后使用recvfrom函数接收服务器发回的消息。

服务器程序

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(void) {
 int i;
 int sfd = socket(AF_INET, SOCK_DGRAM, 0);
 struct sockaddr_in addr;
 addr.sin_family = AF_INET;
 addr.sin_port = htons(9898);
 inet_aton("192.168.204.200", &addr.sin_addr);
 int r = bind(sfd, (struct sockaddr*) & addr, sizeof(addr));
 if (r == -1) perror("bind"), exit(1);
 
 char buf[1024];
 struct sockaddr_in paddr;
 socklen_t len = sizeof(paddr);
 
 while (1) {
  memset(buf, 0x00, sizeof(buf));
  recvfrom(sfd, buf, 1024, 0, (struct sockaddr*) & paddr, &len);
  //为了验证是服务器发回来的消息,我们把消息小写转大写再发回去
  for (i = 0; buf[i] != '\0'; i++)
   if (buf[i] >= 'a' && buf[i] <= 'z')
    buf[i] -= 32;
  sendto(sfd, buf, strlen(buf), 0, (struct sockaddr*) & paddr, len);
 }
}

客户端程序

#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(void) {
 int cfd = socket(AF_INET, SOCK_DGRAM, 0);
 char buf[1024] = {};
 struct sockaddr_in addr;
 socklen_t len = sizeof addr;
 addr.sin_family = AF_INET;
 addr.sin_port = htons(9898);
 inet_aton("192.168.204.200", &addr.sin_addr);
 
 while (fgets(buf, 1024, stdin) != NULL) {
  sendto(cfd, buf, strlen(buf), 0, (struct sockaddr*) & addr, len);
  memset(buf, 0x00, sizeof(buf));
  recvfrom(cfd, buf, 1024, 0, NULL, NULL);
  printf("=> %s\n", buf);
 }
}

你可能感兴趣的:(Linux)