获取主机信息

 
#include <assert.h>
#include <iostream>
#include <tchar.h>
#include <WinSock2.h>
using namespace std;

#pragma comment(lib,"Ws2_32.lib")

#define HOSTNAME_LEN 256

void main(int argc,TCHAR*argv[])
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	wVersionRequested = MAKEWORD( 2, 2 );

	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 ) 
	{
		return;
	}

	if ( LOBYTE( wsaData.wVersion ) != 2 ||
		HIBYTE( wsaData.wVersion ) != 2 ) 
	{
			WSACleanup( );
			return; 
	}


	char szHostName[HOSTNAME_LEN] = {0};
	int nRet = gethostname(szHostName,HOSTNAME_LEN);
	assert(0 == nRet);
	cout<<"主机名称是:"<<szHostName<<endl;

	HOSTENT *pHostInfo;
// 	unsigned long lAddr = inet_addr("84.137.88.0");
//	unsigned long lAddr = inet_addr("127.0.0.1");
//	unsigned long lAddr = inet_addr("123.103.14.237");
// 	in_addr inaddr; inaddr.s_addr = lAddr;
// 	pHostInfo = gethostbyaddr((char*)&inaddr,4,AF_INET);
	//pHostInfo = gethostbyname("www.163.com");
	pHostInfo = gethostbyname(szHostName);
	assert(pHostInfo);

	cout<<"主机全名是:"<<pHostInfo->h_name<<endl;
	if(*pHostInfo->h_aliases)
		cout<<"主机别名是:"<<*pHostInfo->h_aliases<<endl;

	char **ppAddress;
	switch (pHostInfo->h_addrtype)
	{
	case AF_INET:
	case AF_INET6:
		ppAddress = pHostInfo->h_addr_list;
		for(;*ppAddress!=NULL;ppAddress++)
		{
			cout<<"主机IP是: "<<inet_ntoa(*(struct in_addr*)(*ppAddress))<<endl;
		}
		cout<<"主机第一个IP是: "<<inet_ntoa(*(struct in_addr*)(pHostInfo->h_addr_list[0]))<<endl;
		break;
	default:
		cout<<"unknown address type"<<endl;
		break;
	}

	WSACleanup( );
}

你可能感兴趣的:(struct,list,include)