获取本机计算机名和IP地址

看书学习,温故而知新,存档备用。

#include 
#include 
#pragma comment(lib,"WS2_32")

int main()
{
	//1
	WSADATA wsData;
	ZeroMemory(&wsData,sizeof(wsData));
	if(0!=::WSAStartup(MAKEWORD(2,2),&wsData))
	{
		printf("Socket init fail!\r\n");
		return -1;
	}
	//2
	char szHostName[255];
	ZeroMemory(szHostName,sizeof(szHostName));
	if(0!=::gethostname(szHostName,sizeof(szHostName)))
	{
		printf("gethostname fail!\r\n");
		return -1;
	}
	printf("Local Name:%s\r\n",szHostName);
	//3
	HOSTENT* pHostEnt=::gethostbyname(szHostName);
	if(NULL==pHostEnt)
	{
		printf("gethostbyname fail!\r\n");
		return -1;
	}
	in_addr addr;
	for (int i=0;;i++)
	{
		char* temp=pHostEnt->h_addr_list[i];
		if(NULL==temp){break;}
		memcpy(&addr.S_un.S_addr,temp,pHostEnt->h_length);
		char* szIP=::inet_ntoa(addr);
		printf("Local IP(%d):%s\r\n",i,szIP);
	}
	//4
	::WSACleanup();
	//5
	return 0;
}


你可能感兴趣的:(C/C++)