简体   繁体   中英

Select between TCP socket and UDP socket(c)

i'm making a server in c that handles both a tcp connection for an admin to change server configs and a udp connection to handle multiple clients

Here is my code:

    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
      }

    }
           

When i run this code, and try to test it with a udp client it doesnt do anything

However you can use ports below 1024 if you run the program as root and have no other programs running, that already use that ports...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM