如何在Windows下获取IP地址 [英] How to get the ip address under Windows
问题描述
全部 我已经有一个"socketfd",我想知道如何使用它来检索本地IP地址. 在linux下,我可以做这样的事情(不完全正确):
all i already had a "socketfd", and i was wondering how to use it to retrieve the local ip address. under linux, i can do something like this(not exactly correct):
struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;
ioctl(socketfd, SIOCGIFADDR, &ifr);
char *address = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
但是,在Windows上,我如何实现相同的目标? (不使用MFC) 非常感谢.
but, on Windows, how can i achieve the same goal? (not using MFC) many thanks.
也许我的主机有多个ip地址,我希望一个与"socketfd"连接".
edit: maybe my host has multiple ip addresses, and i want the one "connected" with "socketfd".
推荐答案
如果已连接套接字,则其上的getsockname()
将用套接字的本地名称填充struct sockaddr
.在两个操作系统(以及所有带有BSD插槽的操作系统)上都可以使用.
If the socket is connected, then getsockname()
on it will fill a struct sockaddr
with the local name for the socket. This works on both OSes (and anything with BSD sockets).
这篇关于如何在Windows下获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!