VC怎么取得本地IP地址?
VC怎么取得本地IP地址?
[解决办法]
gethostbyname
The Windows Sockets gethostbyname function retrieves host information corresponding to a host name from a host database.
struct hostent FAR * gethostbyname (
const char FAR * name
);
[解决办法]
gethostname
The Windows Sockets gethostname function returns the standard host name for the local machine.
int gethostname (
char FAR * name,
int namelen
);
这两个函数是不一样的
[解决办法]
系统自己有Api函数可以获取本机Ip啊,在Socket类里,你查下Msdn
[解决办法]
先用gethostname得到自己的机器名
再用gethostbyname得到自己机器名对应的ip
代码:
gethostname(HostName, sizeof(HostName));// 获得本机主机名.
hostent* hn;
hn = gethostbyname(HostName);//根据本机主机名得到本机ip
CString strIPAddr;
strIPAddr=inet_ntoa(*(struct in_addr *)hn->h_addr_list[0]);//把ip换成字符串形式
[解决办法]
//先用gethostname得到自己的机器名 //再用gethostbyname得到自己机器名对应的ip //代码: gethostname(HostName, sizeof(HostName));// 获得本机主机名. hostent* hn; hn = gethostbyname(HostName);//根据本机主机名得到本机ip CString strIPAddr; strIPAddr=inet_ntoa(*(struct in_addr *)hn->h_addr_list[0]);//把ip换成字符串形式
[解决办法]
学习下
[解决办法]
IP_ADAPTER_INFOm_AdapterInfo[16];
DWORD dwBufLen = sizeof(m_AdapterInfo);
if (GetAdaptersInfo( // Call GetAdapterInfo
m_AdapterInfo, // [out] buffer to receive data
&dwBufLen) != ERROR_SUCCESS)
{
return 0;
}
[解决办法]
CString CUtil::GetLocalIp()
{
struct hostent * phost;
char ip[20];
char hostname[50];
gethostname(hostname, 50);
phost = gethostbyname(hostname);
char * * names;
names = phost->h_aliases;
char * * iplist;
iplist = phost->h_addr_list;
while (* iplist)
{
strcpy(ip, inet_ntoa(* (struct in_addr *) * iplist));
iplist++;
}
CString LocalIp = ip;
return LocalIp;
}