首页 > 编程 > C > 正文

教你用C语言获取电脑的IP地址

2020-02-24 14:34:18
字体:
来源:转载
供稿:网友

对于C语言,小编有自己的一些心得体会,也请C语言高手多多指教~那接下来武林技术频道的小编就教你用C语言获取电脑的IP地址,一起来了解下其中的详情吧。

复制代码 代码如下:

#include
#include

#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() finish use Winsock 2 DLL (Ws2_32.dll). Head:Winsock2.h. reference #pragma comment(lib, "ws2_32.lib") */
WSACleanup();
return 0;
}

武林技术小编教你用C语言获取电脑的IP地址,有没有觉得特别的实用呢,更多关于C语言的内容,可以多多关注下武林技术频道,我们会不断的更新。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选