-1

I need to bind my server to a dynamic port (use an ephermal port) but call to bind() when port is specified to be 0 (which means any random port) is always binding the server to port 0.

//Sample code snippet

int sockfd;
struct sockaddr_in serv_addr;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
   error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(INADDR_ANY);  //randomly selected port
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
  error("ERROR on binding");

listen(sockfd,5);

printf("Port no. is %d",ntohs (serv_addr.sin_port));
close(sockfd);
user3111166
  • 1
  • 1
  • 2
  • 2
    Why are you setting `sin_port` to `htons(INADDR_ANY)` instead of `0`? This doesn't make sense semantically speaking. Additionally, you should use `getsockname` to find the actual socket your server is listening on. – user703016 Dec 19 '13 at 09:58

1 Answers1

2

You seem to be inventing your own semantics.

If you look at the bind(2) manpage you'll see that the second argument is const struct sockaddr *addr and yet you are expecting it to be updated after the call to bind().

See this SO question to find out how to determine which port was assigned within bind().

Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242