windows windows下如何获取ip地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5114305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the ip address under Windows
提问by Heisenburgor
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):
我已经有了一个“socketfd”,我想知道如何使用它来检索本地 IP 地址。在 linux 下,我可以做这样的事情(不完全正确):
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);
but, on Windows, how can i achieve the same goal? (not using MFC) many thanks.
但是,在 Windows 上,我如何才能实现相同的目标?(不使用 MFC)非常感谢。
edit: maybe my host has multiple ip addresses, and i want the one "connected" with "socketfd".
编辑:也许我的主机有多个 ip 地址,我想要一个与“socketfd”“连接”的地址。
回答by Sergey Vedernikov
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
CString ip;
PHOSTENT hostinfo;
wVersionRequested = MAKEWORD( 2, 0 );
if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
{
if( gethostname ( name, sizeof(name)) == 0)
{
if((hostinfo = gethostbyname(name)) != NULL)
{
ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
}
}
WSACleanup( );
}
with #include <winsock2.h>
和 #include <winsock2.h>
回答by caf
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).
如果套接字已连接,则getsockname()
在它上面填充struct sockaddr
套接字的本地名称。这适用于两种操作系统(以及任何带有 BSD 套接字的操作系统)。