Reputation: 11
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...
Upvotes: 1
Views: 528