我怎样才能知道C中接口的IP地址?
假设我正在运行一个名为 IpAddresses.c 的程序。我希望该程序根据每个接口获取该设备拥有的所有 IP 地址。就像 ifconfig 一样。我怎样才能做到这一点?
我对 ioctl 了解不多,但我读过它可能对我有帮助。
Let's say I'm running a program called IpAddresses.c. I want that program to get all IP addresses this device has according to each interface. Just like ifconfig. How can I do that?
I don't know much about ioctl, but I read it might help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
只需使用 getifaddrs() 即可。这是一个例子:
这是我在我的机器上得到的输出:
Just use getifaddrs(). Here's an example:
And here's the output I get on my machine:
这里有一些 Linux 示例代码可能会对您有所帮助。
Here's some Linux sample code that might help you out.
使用 getifaddrs() 的解决方案是伟大的。我只建议一项改进:
只是因为我自己遇到了分段错误。
The solution using getifaddrs() is great. I would suggest only one improve:
Just because I myself got a Segmentation Fault.
请参阅另一个 Stack Overflow 问题,枚举分配给的每个 IP 地址网络接口。
总之,您可以使用:
ioctl(SIOCGIFCONF)
->传统的 ioctlgetifaddrs()
->来自 BSDi,现在也可以在 Linux 和 BSD 上使用。See this other Stack Overflow question, Enumerating each IP address assigned to network interfaces.
In summary, you can use:
ioctl(SIOCGIFCONF)
-> the traditional ioctlgetifaddrs()
-> from BSDi, now also on Linux and the BSD's.你可以尝试这样的事情:
You could try something like that:
查看(特定于 Windows)IP Helper API - 幸运的是,在 Windows 上您不需要
ioctl
来实现此目的。Check out the (Windows specific) IP Helper API - fortunately you don't need
ioctl
for this on Windows.如果您还需要 IP6 地址,您可以像这样扩展接受的答案:
In case you also need IP6 addresses, you can extend the accepted answer like this: