由域名获取IP地址

#include<WinSock2.h>
#include<assert.h>
#include<WS2tcpip.h>
#include<stdio.h>

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

const char *domain = "www.baidu.com";


int main()
{
	int nError;
	WSADATA wsaData;

	nError = ::WSAStartup(MAKEWORD(2, 2), &wsaData);
	assert(nError != 0);

	in_addr remote_addr;
	hostent *hptr = NULL;
	char **pptr;
	char str[MAX_PATH];


	if ((hptr = (hostent *)gethostbyname(domain)) == NULL) {

		int err = WSAGetLastError();
		return 0;
	}

	if (hptr->h_addrtype == AF_INET) {

		pptr = hptr->h_addr_list;

		for (; *pptr != NULL; pptr++) {

			printf("%s\n", inet_ntop(hptr->h_addrtype,
				*pptr,
				str,
				sizeof(str)));
		}
	}

	return 0;
}
发布了140 篇原创文章 · 获赞 65 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/paradox_1_0/article/details/100973938