gethostbyname, gethostbyaddr

☆樱花仙子☆ 提交于 2020-02-09 01:29:29

gethostbyname取ip地址, gethostbyaddr取域名

#include <iostream>

// #ifndef WIN32_LEAN_AND_MEAN
// #define WIN32_LEAN_AND_MEAN
// #endif

#include <winsock2.h>
#include <windows.h>
#include <conio.h>

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

using std::cout;
using std::endl;
using std::cerr;

int main(int argc,char *argv[],char *envp[])
{
	int iretcode = 0;
	const char *pip_addr = "www.baidu.com";//or "220.181.38.148";//

	WSADATA wsa = {0};
	iretcode = WSAStartup(MAKEWORD(2,2),&wsa);
	if(iretcode != 0)
		return iretcode;// WSAStartup function error.

	///////////////////////////////////////////////
	// get address dwip_addr of network byte order.
	unsigned long dwip_addr = inet_addr(pip_addr);// to struct in_addr
	if(dwip_addr == INADDR_NONE)
	{
		struct hostent *phentry = NULL;
		phentry = gethostbyname(pip_addr);// to struct hostent
		if(phentry != NULL)
			dwip_addr = *( (unsigned long *)(phentry->h_addr_list[0]) );//take the first address of the domain name.
	}
	///////////////////////////////////////////////
	cout<<std::hex<<"ip address (network byte order): "<<dwip_addr<<endl;
	

	// get ip
	cout<<"ip address: "<<inet_ntoa(*((struct in_addr *)&dwip_addr) )<<endl;// to char * address.

	// get domain name
	struct hostent *phe = gethostbyaddr((char *)&dwip_addr,sizeof(dwip_addr),AF_INET);// to struct hostent
	cout<<"domain name: "<<phe->h_name<<endl;


	cout<<std::hex<<"ip address (network byte order): "<<*((unsigned long *)phe->h_addr_list[0])<<endl;

	WSACleanup();
	cout<<"press any key to quit."<<endl;
	_getch();
	return iretcode;
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!