getsockname() 没有 bind()

getsockname() without bind()

我试图在不调用 bind() 的情况下获取套接字的端口号。 代码如下。

#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));
  }
}

它总是打印 "port number 0".

是否必须调用bind()才能使用getsockname()?我在网上看到类似的说法,但我找不到可靠的说法。

来自手册页:

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.

来自POSIX getsockname,粗体是我的。

所以是的,你需要绑定套接字。