WinSocket 获取当前主机 IP 代码

// SocketLearning2.cpp : Defines the entry point for the console application. // //Additional Dependecies: wsock32.lib #include "stdafx.h" #include <winsock.h> // this header file is under %systemdrive%/Program Files/Microsoft SDKs/Windows/v6.0A/Include #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { WSADATA wSADATA; if(0 != WSAStartup(WORD(0x0101),&wSADATA)) //WORD is 16 bit, 0x0101 is 4*4 bit = 16 bit; return 0, means OK { cout << "Failed to startup winsocket" << endl; return 1; } char hostname[256]; if(0 != gethostname(hostname, 256)) //return 0, means OK { cout << "Failed to get hostname" << endl; return 2; } hostent * pHostent; // this struct seems don't need to initialized before get returned value of gethotbyname() pHostent = gethostbyname(hostname); //pHostent->h_addr_list[0] means the current host's IP if(NULL != pHostent) { printf("%d.%d.%d.%d", ((pHostent->h_addr_list[0][0])&0x00ff), //Only get last char(8 bit) ((pHostent->h_addr_list[0][1])&0x00ff), ((pHostent->h_addr_list[0][2])&0x00ff), ((pHostent->h_addr_list[0][3])&0x00ff)); } WSACleanup(); // Close network device, reclaim resource return 0; }

你可能感兴趣的:(list,struct,header,File,null,NetWork)