我用它作为地址来创建一个新服务器(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);
宏 UNUSED_PORT 定义为 0。
我希望服务器能够监听任何接口和未使用的端口。
我尝试使用getsockname()
获取我的本地 IP 地址和端口,但我得到了一些奇怪的输出。输出代码如下:
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));
例如,我得到 0.255.255.255:0、0.0.0.0:0、255.127.0.0:36237 等。
我的系统是Mac OS X 10.7.3。
- 更新 -
使用后socklen_t addressLength = sizeof(localAddress);
(感谢@cnicutar和@Jonathan Leffler),我总是得到0.0.0.0作为本地IP;可以吗?