C語言獲得電腦的IP地址的小例子
更新時間:2013年05月15日 09:40:18 作者:
C語言獲得電腦的IP地址的小例子,需要的朋友可以參考一下
復(fù)制代碼 代碼如下:
#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() finish use Winsock 2 DLL (Ws2_32.dll). Head:Winsock2.h. reference #pragma comment(lib, "ws2_32.lib") */
WSACleanup();
return 0;
}
您可能感興趣的文章:
相關(guān)文章
vector, list, map在遍歷時刪除符合條件的元素實現(xiàn)方法
下面小編就為大家?guī)硪黄獀ector, list, map在遍歷時刪除符合條件的元素實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12
C語言基本排序算法之插入排序與直接選擇排序?qū)崿F(xiàn)方法
這篇文章主要介紹了C語言基本排序算法之插入排序與直接選擇排序?qū)崿F(xiàn)方法,結(jié)合具體實例形式分析了插入排序與直接選擇排序的定義、使用方法及相關(guān)注意事項,需要的朋友可以參考下2017-09-09
C++ 中動態(tài)鏈接庫--導(dǎo)入和導(dǎo)出的實例詳解
這篇文章主要介紹了C++ 中動態(tài)鏈接庫--導(dǎo)入和導(dǎo)出的實例詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下2017-09-09

