0

I'm writing a client-server application via udp. I did these steps:

memset((void *)&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(serverport); 
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) < 0)
err_func("Error in inet_pton()\n");
...
if( (socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
err_func("Error in socket()");
...
if(sendto(socketfd,&pckt, sizeof(pckt), 0, (struct sockaddr *)&servaddr,sizeof(servaddr)) == -1)
err_func("Error in sendto()\n");
...
struct sockaddr_in addr;
socklen_t len;
if(getsockname(socketfd,(struct sockaddr *) &addr, &len) != 0)
err_func("Error in getsockname()\n"); 
printf("My port is %d\n", addr.sin_port);

Now my problem is that this code will print "My port is 0", but why? and how is it possible? (0 is a jolly that means "the SO will assign a port randomly that is not used", but after a sendto the SO has have assigned a port to my socket, or not ?)

The strange thing is that after 2 or 3 sendto, my code start to print a different value for addr.sin_port. Why doest it not work fine since the first sendto?

I need it bind a port because on server I create a process that execute connect with that client address and he will receive all packets from the client.

I tried to run a bind into the client before run the first sendto, but it seems like bind has no effect (probably I fill the struct sockaddr_in used in bind wrong? I don't know).

If you need I can post all the code from running main... I send the first packet early...

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Possible duplicate of https://stackoverflow.com/a/19621082/1076479. By the way, you don't need to post *all* the code if it's large, but you should post a [mcve]. That way, someone else can easily copy your code, paste it into a file, compile it and duplicate your results. – Gil Hamilton Dec 03 '18 at 22:45
  • 1
    You need to set `socklen_t len = sizeof(addr);` before calling `getsockname()` – Jeremy Friesner Dec 04 '18 at 03:52
  • @JeremyFriesner yes, the same problem was on server side, before calling `recvfrom()` i did not initialize len. Thank you. – George Lucas Dec 04 '18 at 07:42

0 Answers0