之前用其他简单方法获取过ip地址, 下面我们尝试用另外的方法获取。 如果你编译出现错误, 请在我的博客资源中下载对应的头文件和库。
直接上菜:
#include <stdio.h>
#include <winsock2.h>
#include <iphlpapi.h> // 如果没有这个, 请在我的博客资源中下载
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
int main()
{
unsigned long size = 0;
PMIB_IPADDRTABLE pIPAddrTable = (MIB_IPADDRTABLE *)malloc(sizeof(MIB_IPADDRTABLE));
if (GetIpAddrTable(pIPAddrTable, &size, 0) == ERROR_INSUFFICIENT_BUFFER)
{
free(pIPAddrTable);
pIPAddrTable = (MIB_IPADDRTABLE *)malloc(size);
}
GetIpAddrTable( pIPAddrTable, &size, 0 );
// 为了用inet_ntoa
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup(wVersionRequested, &wsaData);
int i = 0;
IN_ADDR IPAddr;
for(i = 0; i < (int)pIPAddrTable->dwNumEntries; i++)
{
IPAddr.S_un.S_addr = (unsigned long)pIPAddrTable->table[i].dwAddr;
printf("IP地址:%s\n", inet_ntoa(IPAddr));
}
free(pIPAddrTable);
printf("\n");
return 0;
}
结果为:
IP地址:192.168.1.101
IP地址:127.0.0.1