当前位置:主页 > 软件编程 > C代码 >

Linux UDP服务端和客户端程序的实现

时间:2021-05-11 08:55:19 | 栏目:C代码 | 点击:

1. 源码

UDP服务端:

/**
 * @brief  UDP服务端
 * @author Mculover666
 * @date  2020/04/15
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{

  int server_sock_fd;
  struct sockaddr_in server_addr, client_addr;
  char recv_buf[100];
  int nbytes = 0;
  socklen_t len = 0;

  /* 创建Server Socket */
  server_sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
  if (server_sock_fd < 0)
  {
    printf("服务端Socket创建失败");
    return -1;
  }
  printf("服务端Socket创建成功\n");

  /* 绑定ip和端口 */
  bzero(&server_addr, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(atoi(argv[1]));//指定端口号
  bind(server_sock_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));

  printf("服务端Socket绑定成功\n");
  
  while(1)
  {
    /* 接收UDP客户端的数据 */
    printf("等待接收客户端数据:\n");
    len = sizeof(client_addr);
    nbytes = recvfrom(server_sock_fd, recv_buf, 100, 0, (struct sockaddr *)&client_addr, &len);
    printf("ok\n");
    recv_buf[nbytes] = '\0';
    printf("recv %d bytes:%s.\n", nbytes, recv_buf);

    //接收用户输入,发送给客户端
    printf("请输入要发送给客户端的数据:");
    fgets(recv_buf, 100, stdin);
    sendto(server_sock_fd,recv_buf,strlen(recv_buf),0,(struct sockaddr *)&client_addr,len);
  }

  return 0;
}

UDP客户端:

/**
 * @brief  UDP客户端程序
 * @author Mculover666
 * @date  2020/04/15
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
  int sock_fd;
  struct sockaddr_in server_addr;
  char recv_buf[100];
  int nbytes = 0;
  socklen_t len = 0;

  /* 创建Socket */
  sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sock_fd < 0)
  {
    printf("客户端Socket创建失败");
    return -1;
  }

  /* 绑定ip和端口 */
  bzero(&server_addr, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = inet_addr(argv[1]);
  server_addr.sin_port = htons(atoi(argv[2]));//指定端口号
  while(1)
  {
	  len = sizeof(server_addr);
    //接收用户输入,发送给服务端
    printf("请输入要发送给服务端的数据:");
	  fgets(recv_buf, 100, stdin);
    sendto(sock_fd,recv_buf,100,0,(struct sockaddr *)(&server_addr),len);
    
    /* 接收UDP客户端的数据 */
    len = sizeof(server_addr);
    nbytes = recvfrom(sock_fd, recv_buf, 100, 0, (struct sockaddr *)&server_addr, &len);
    recv_buf[nbytes] = '\0';
    printf("recv %d bytes:%s.\n", nbytes, recv_buf);
  
  }

  return 0;
}

2. 在本机运行结果

编译:

gcc server.c -o srever_wangshiwei.o
gcc client.c -o client_wangshiwei.o

运行:


3. 在开发板与PC之间运行结果

编译:

gcc server.c -o srever_wangshiwei.o
arm-linux-gnueabi-gcc client.c -o clientARM_wangshiwei.o


您可能感兴趣的文章:

相关文章