0

I'm trying to get the port number of the socket, without calling bind(). The code is as follows.

#include <arpa/inet.h>
#include <unistd.h>
#include <cstdio>
int main() {
  int sock = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  struct sockaddr_in sin;
  socklen_t len = sizeof(sin);
  if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1) {
      perror("getsockname");
  } else {
      printf("port number %d\n", ntohs(sin.sin_port));
  }
}

it always print "port number 0".

Is it mandatory to call bind() to use getsockname()? I saw similar statement mentioned from internet, but i cannot find a solid statement.

pepero
  • 7,095
  • 7
  • 41
  • 72

1 Answers1

1

From man page:

The getsockname() function shall retrieve the locally-bound name of the specified socket,

(...)

If the socket has not been bound to a local name, the value stored in the object pointed to by address is unspecified.

from POSIX getsockname, bold are mine.

So yes, you need to bind the socket.

Community
  • 1
  • 1
Giacomo Catenazzi
  • 8,519
  • 2
  • 24
  • 32