简体   繁体   中英

How to get local IP address and port in Unix socket programming?

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?

您需要在调用getsockname之前初始化addressLength

socklen_t addressLength = sizeof(localAddress);

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?

However it works fine when there is an incoming connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM