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.