域名及IP地址

这段代码演示了在LINUX和Windows平台上使用gethostbyname和gethostbyaddr函数进行IP地址和域名的解析。程序首先通过域名获取主机信息,然后显示主域名、IP地址长度、地址族等信息。接着,它使用IP地址反向查询域名,再次展示相关信息。
摘要由CSDN通过智能技术生成

LINUX平台

	auto host = gethostbyname("www.bdjw.work");
	if (host) {

		//主域名
		std::cout << host->h_name << endl;
		//ip地址长度,ipv4是4字节
		std::cout << host->h_length << endl;
		//IP地址族信息
		if (AF_INET == host->h_addrtype)
			std::cout << "AF_INET" << endl;
		else
			std::cout << host->h_addrtype << endl;
		//如果有其它域名,是由h_aliases保存
		for (size_t i = 0; host->h_aliases[i]; i++)
			std::cout << host->h_aliases[i] << endl;
		//IP地址列表
		for (size_t i = 0; host->h_addr_list[i]; i++)
			std::cout << inet_ntoa(*(in_addr*)host->h_addr_list[i]) << endl;

	}

	sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_addr.s_addr = inet_addr("101.43.87.248");
	host = gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET);
	if (host) {

		//主域名
		std::cout << host->h_name << endl;
		//ip地址长度,ipv4是4字节
		std::cout << host->h_length << endl;
		//IP地址族信息
		if (AF_INET == host->h_addrtype)
			std::cout << "AF_INET" << endl;
		else
			std::cout << host->h_addrtype << endl;
		//如果有其它域名,是由h_aliases保存
		for (size_t i = 0; host->h_aliases[i]; i++)
			std::cout << host->h_aliases[i] << endl;
		//IP地址列表
		for (size_t i = 0; host->h_addr_list[i]; i++)
			std::cout << inet_ntoa(*(in_addr*)host->h_addr_list[i]) << endl;

	}

Windows平台

	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
		cout << "WSAStartup() error" << endl;

	auto host = gethostbyname("www.bdjw.work");
	if (host) {

		//主域名
		std::cout << host->h_name << endl;
		//ip地址长度,ipv4是4字节
		std::cout << host->h_length << endl;
		//IP地址族信息
		if (AF_INET == host->h_addrtype)
			std::cout << "AF_INET" << endl;
		else
			std::cout << host->h_addrtype << endl;
		//如果有其它域名,是由h_aliases保存
		for (size_t i = 0; host->h_aliases[i]; i++)
			std::cout << host->h_aliases[i] << endl;
		//IP地址列表
		for (size_t i = 0; host->h_addr_list[i]; i++)
			std::cout << inet_ntoa(*(in_addr*)host->h_addr_list[i]) << endl;

	}

	SOCKADDR_IN addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_addr.s_addr = inet_addr("101.43.87.248");
	host = gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET);
	if (host) {

		//主域名
		std::cout << host->h_name << endl;
		//ip地址长度,ipv4是4字节
		std::cout << host->h_length << endl;
		//IP地址族信息
		if (AF_INET == host->h_addrtype)
			std::cout << "AF_INET" << endl;
		else
			std::cout << host->h_addrtype << endl;
		//如果有其它域名,是由h_aliases保存
		for (size_t i = 0; host->h_aliases[i]; i++)
			std::cout << host->h_aliases[i] << endl;
		//IP地址列表
		for (size_t i = 0; host->h_addr_list[i]; i++)
			std::cout << inet_ntoa(*(in_addr*)host->h_addr_list[i]) << endl;

	}
	WSACleanup();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值