域名获取IP

#include <Winsock2.h>  
#include <stdio.h>
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment (lib, "Ws2_32.lib")


int main(void)
{

	
	printf("%d\n", htons(80));
	printf("%d\n", ntohs(20480));
	printf("%d\n", htonl(649189134));

	WORD wVersion;
	WSADATA WSAData;
	wVersion = MAKEWORD(2, 2);
	WSAStartup(wVersion, &WSAData);
	struct addrinfo hints;
	struct addrinfo *res, *cur;
	int ret;
	struct sockaddr_in *addr;
	char m_ipaddr[16];

	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_INET;     /* Allow IPv4 */
	hints.ai_flags = AI_PASSIVE;/* For wildcard IP address */
	hints.ai_protocol = 0;         /* Any protocol */
	hints.ai_socktype = SOCK_STREAM;

	ret = getaddrinfo("www.baidu.com", NULL, &hints, &res);

	if (ret == -1) {
		perror("getaddrinfo");
		exit(1);
	}
	for (cur = res; cur != NULL; cur = cur->ai_next) {
		addr = (struct sockaddr_in *)cur->ai_addr;
		sprintf(m_ipaddr, "%d.%d.%d.%d",
			(*addr).sin_addr.S_un.S_un_b.s_b1,
			(*addr).sin_addr.S_un.S_un_b.s_b2,
			(*addr).sin_addr.S_un.S_un_b.s_b3,
			(*addr).sin_addr.S_un.S_un_b.s_b4);
		printf("getaddrinfo:%s\n", m_ipaddr);
	}
	freeaddrinfo(res);

	hostent* remoteHost = gethostbyname("www.baidu.com");
	if (remoteHost)
	{
		if (remoteHost->h_addrtype == AF_INET)
		{
			int i = 0;
			in_addr addr;
			while (remoteHost->h_addr_list[i] != 0)
			{
				 addr.S_un.S_addr = *(u_long *)remoteHost->h_addr_list[i++];
				printf("gethostbyname:IP Address #%d: %s\n", i, inet_ntoa(addr));
			}
		}
	}

	getchar();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值