C语言获得电脑的IP地址的小例子

时间:2021-05-20

复制代码 代码如下:
#include <stdio.h>
#include <winsock2.h>

#pragma comment(lib, "WS2_32.lib")

int main()
{
char host_name[256]; // define host name (for example:xxx-PC)
int WSA_return, i;
WSADATA WSAData;
HOSTENT *host_entry; // record host information
WORD wVersionRequested;


wVersionRequested = MAKEWORD(2, 0);
WSA_return = WSAStartup(wVersionRequested, &WSAData); // initialize Winsock service and then call other socket or dll file

if (WSA_return == 0) // initialize success
{
gethostname(host_name, sizeof(host_name));
host_entry = gethostbyname(host_name);

for(i = 0; host_entry != NULL && host_entry->h_addr_list[i] != NULL; ++i)
{
// define pszAddr to record IP
// inet_ntoa: Convert an IP into an Internet standard dotted format string
const char *pszAddr = inet_ntoa (*(struct in_addr *)host_entry->h_addr_list[i]);
printf("[IP]\t%s\n[Name]\t%s\n\n", pszAddr, host_name);
}
}
else
{
printf("ERROR\n");
}

WSACleanup();
return 0;
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章