最近想一寫一個用C語言實現擷取PC的IP地址的程式,不過可能是還是在入門,沒有自己的代碼,下面的是我在網上download的。
注釋是我自己添加的,也就這個小程式上網度娘了不少的介紹,不一個地方不是很懂,那就是這個程式在我的機子上跑了之後會擷取兩個不同IP地址。
很奇怪,不是嗎?不過我通過在運行裡運行ipconfig後得出一個結論那就是第一個是正確的,後面那個不知道是什麼東西,看著也不像子網路遮罩。
相關函數會在後面給出串連。
CODE:
1 #include <stdio.h> 2 #include <winsock2.h> 3 4 #pragma comment(lib, "WS2_32.lib") 5 6 int main() 7 { 8 char host_name[256]; // define host name (for example:xxx-PC) 9 int WSA_return, i;10 WSADATA WSAData;11 HOSTENT *host_entry; // record host information12 WORD wVersionRequested;13 14 15 wVersionRequested = MAKEWORD(2, 0);16 WSA_return = WSAStartup(wVersionRequested, &WSAData); // initialize Winsock service and then call other socket or dll file17 18 if (WSA_return == 0) // initialize success19 {20 gethostname(host_name, sizeof(host_name));21 host_entry = gethostbyname(host_name);22 23 for(i = 0; host_entry != NULL && host_entry->h_addr_list[i] != NULL; ++i)24 {25 // define pszAddr to record IP26 // inet_ntoa: Convert an IP into an Internet standard dotted format string27 const char *pszAddr = inet_ntoa (*(struct in_addr *)host_entry->h_addr_list[i]);28 printf("[IP]\t%s\n[Name]\t%s\n\n", pszAddr, host_name);29 }30 }31 else32 {33 printf("ERROR\n");34 }35 /* WSACleanup() finish use Winsock 2 DLL (Ws2_32.dll). Head:Winsock2.h. reference #pragma comment(lib, "ws2_32.lib") */36 WSACleanup();37 return 0;38 }
WSADATA:http://baike.baidu.com/view/2297317.htm
HOSTENT:http://baike.baidu.com/view/2964753.htm
MAKEWORD:http://baike.baidu.com/view/1385564.htm
WSAStartup:http://baike.baidu.com/view/2794415.htm
gethostname:http://baike.baidu.com/view/569231.htm
gethostbyname:http://baike.baidu.com/view/569229.htm
inet_ntoa:http://baike.baidu.com/view/4786779.htm
WSACleanup:http://baike.baidu.com/view/573402.htm