简体   繁体   中英

Why UDP socket doesn't receive udp traffic from nc -u host port?

 int main(int argc, char *argv[])
 {
     struct sockaddr_in src = { .sin_family=AF_INET, .sin_addr.s_addr=INADDR_ANY, .sin_port=htons(90) };

     int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);

     bind(fd, (struct sockaddr *)&src, sizeof(src));

     char buf[1024];
     ssize_t res = recvfrom(fd, buf, sizeof(buf), 0, NULL, 0);
     printf("res=%zi\n", res);

     return 0;
 }

After compiling and execute this program. On another terminal I execute

nc -u localhost 90

to test if I'm actually receiving some udp traffic from "any interface" as I would expect since I've used INADDR_ANY. But the programs just hangs. What am I missing?

port 90 is less than 1024 so a process requires privileges in order to bind a socket to it.

You have two options:

  1. choose a port above 1024
  2. run your program with privileges (sudo...)

One should consider testing the result of bind() (as any other system call in general) to easily detect such situations.

I wasn't providing enough data through nc . I was facing two situation:

nc -u localhost 1025

The program was hanging....obviously because I didn't pass nothing except from '\\n' which wasn't received by the socket.

nc -u -v localhost 1025

I was still passing just '\\n' but in this case the socket was receiving it.

Writing a bunch of characters worked in both cases.

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