Reputation: 11
self._socket = socket(AF_INET, SOCK_DGRAM, 0);
// create addr
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(0);
addr.sin_addr.s_addr = INADDR_ANY;
// bind socket
bind(self._socket, (struct sockaddr *)&addr, sizeof(addr));
printf("befor getsockname()->%d\n", ntohs(addr.sin_port));
socklen_t len = sizeof(addr);
getsockname(self._socket, (struct sockaddr *)&addr, &len); // if i comment this func, the last printf() will print 0; if not, it will print a real in use udp port(and it is correct!)
printf("after getsockname()->%d\n", ntohs(addr.sin_port));
So, is that when assign htons(0) to a port, the local socket must use getsockname() to assign a available port to itself? Or anything else? I think this is maybe because i just bind 0 to sin_port which mean to assign a random port but has not assigned by system yet, so just call getsockname() to make system really assign a port.
Upvotes: 1
Views: 855
Reputation: 310869
So, is that when assign htons(0) to a port, the local socket must use getsockname() to assign a available port to itself? Or anything else?
No, you must use bind()
to assign a port to the socket. getsockname()
tells you what port was assigned if you specified zero.
Upvotes: 2
Reputation: 215193
The whole point of the getsockname
function is to get the sockaddr
for the local side of the socket. For IPv4 sockets, this is an object of type sockaddr_in
and it contains both the IP address and port.
Upvotes: 0