OpSys Spring 2005 - HW5 FAQ

Click on a question to expand it (for the details).
Click on the question title again to hide the details.

+ Server port number?

Question:

If I tell bind the port is 0, which means "give me any available port", how do I find out what the port is (so I can print it out)?


Answer:

After the call to bind(), you can call getsockname and give it a sockaddr to fill in with your local address. Below is some sample code (man getsockname for details).

  /* find out what port we were assigned and print it out */                                                             
  length = sizeof( skaddr );
  if (getsockname(ld, (struct sockaddr *) &skaddr, &length)<0) {
    perror("Error getsockname\n");
    exit(1);
  }
  printf("The Server passive socket port number is %d\n",ntohs(skaddr.sin_port));