如何在Unix套接字编程中获取本地IP地址和端口? [英] How to get local IP address and port in Unix socket programming?

查看:384
本文介绍了如何在Unix套接字编程中获取本地IP地址和端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用它作为创建新服务器的地址( socket() bind() listen()):

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);

宏UNUSED_PORT定义为0.

The macro UNUSED_PORT is defined as 0.

我希望服务器能够监听任何接口和未使用的端口。

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

我试图使用 getsockname()获取我的本地IP地址和端口,但我得到了一些奇怪的输出。输出代码如下:

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));

例如,我得到0.255.255.255:0,0.0.0.0:0,255.127.0.0: 36237等等
我的系统是Mac OS X 10.7.3。

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.

- 更新 -

使用 socklen_t addressLength = sizeof(localAddress); (感谢@cnicutar和@Jonathan Leffler),我总是得到0.0.0.0的本地IP;可以吗?

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?

推荐答案

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

You need to initialize addressLength before calling getsockname:

socklen_t addressLength = sizeof(localAddress);

这篇关于如何在Unix套接字编程中获取本地IP地址和端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆