How to get local IP address and port in Unix socke

2020-03-26 05:59发布

I used this as the address to create a new server(socket(), bind(), listen()):

struct sockaddr_in newServer;
memset(&newServer, 0, sizeof(newServer));
newServer.sin_family = AF_INET;
newServer.sin_addr.s_addr = htonl(INADDR_ANY);
newServer.sin_port = htons(UNUSED_PORT);

The macro UNUSED_PORT is defined as 0.

I expect to get a server listening on any interface and on an unused port.

I tried to use getsockname() to get my local IP address and port, but I got some strange outputs. The output code as below:

struct sockaddr_in localAddress;
socklen_t addressLength;
getsockname(newServerfd, (struct sockaddr*)&localAddress,   \
                &addressLength);
printf("local address: %s\n", inet_ntoa( localAddress.sin_addr));
printf("local port: %d\n", (int) ntohs(localAddress.sin_port));

For example, I got 0.255.255.255:0, 0.0.0.0:0, 255.127.0.0:36237, etc. and my system is Mac OS X 10.7.3.

--update--

After using socklen_t addressLength = sizeof(localAddress); (thanks to @cnicutar and @Jonathan Leffler), I always get 0.0.0.0 for local IP; is that all right?

1条回答
Summer. ? 凉城
2楼-- · 2020-03-26 06:26

You need to initialize addressLength before calling getsockname:

socklen_t addressLength = sizeof(localAddress);
查看更多
登录 后发表回答