选择 TCP 套接字和 UDP 套接字(c)

问题描述 投票:0回答:1

我正在用 c 语言创建一个服务器,它可以处理 tcp 连接(供管理员更改服务器配置)和 udp 连接来处理多个客户端

这是我的代码:

    struct sockaddr_in si_minhaTCP,si_minhaUDP, si_outra;
    int nready, maxfdp1;
    int fdTcp;
    int fdUdp;
    fd_set rset;
    if (argc != 4) {
    printf("server {client port(udp)} {admin port(tcp)} {registry file path}\n");
    exit(-1);
  }

    fdTcp = socket(AF_INET, SOCK_STREAM, 0);
    bzero(&si_minhaTCP, sizeof(si_minhaTCP));
    si_minhaTCP.sin_family = AF_INET;
    si_minhaTCP.sin_addr.s_addr = htonl(INADDR_ANY);
    si_minhaTCP.sin_port = htons((short) atoi(argv[2]));
    bind(fdTcp, (struct sockaddr*)&si_minhaTCP, sizeof(si_minhaTCP));
    listen(fdTcp, 10);


        
    fdUdp = socket(AF_INET, SOCK_DGRAM, 0);
    si_minhaUDP.sin_family = AF_INET;
    si_minhaUDP.sin_addr.s_addr = htonl(INADDR_ANY);
    si_minhaUDP.sin_port = htons((short) atoi(argv[1]));
    bind(fdUdp, (struct sockaddr*)&si_minhaUDP, sizeof(si_minhaUDP));


    FD_ZERO(&rset);

    maxfdp1 = max(fdTcp, fdUdp) + 1;
    for (;;)
    {
      FD_SET(fdTcp, &rset);
      FD_SET(fdUdp, &rset);
      // select the ready descriptor

      nready = select(maxfdp1, &rset, NULL, NULL, NULL);
      if (FD_ISSET(fdTcp, &rset))
      {

          //handle tcp connection
      }
      if (FD_ISSET(fdUdp, &rset))
      {
          //handle udp connection
      }

    }
           

当我运行此代码并尝试使用 udp 客户端测试它时,它没有执行任何操作

c sockets tcp udp posix-select
1个回答
0
投票

但是,如果您以 root 身份运行该程序并且没有运行其他已使用该端口的程序,则可以使用低于 1024 的端口...

© www.soinside.com 2019 - 2024. All rights reserved.