我将其用作创建新服务器(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。

我希望让服务器在任何接口(interface)和未使用的端口上进行监听。

我尝试使用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。可以吗

最佳答案

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

socklen_t addressLength = sizeof(localAddress);

关于c - 如何在Unix套接字编程中获取本地IP地址和端口?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10167540/

10-08 22:51