C語言獲得PC的IP地址

來源:互聯網
上載者:User

最近想一寫一個用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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.