IP地址与域名之间的转换(Windows + Visual Studio 2015)

注意:博主用的visual studio 2015,在windows调试程序需要链接ws2_32.lib库,才能正常运行程序。

打开项目的“Property”->"Linker"->"Input"->"Additional Dependencies",或者你也可以通过快捷键Alt+F7打开Property页面. 不知如何操作,可以看http://blog.csdn.net/qq_16542775/article/details/51203465.


这里只贴出代码(原理和上一篇IP地址与域名之间的转换(Linux + GCC)相同!这里目的只在于比较二者源代码的异同!)


gethostbyname_win.c

#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include
#include
#include

void ErrorHandling(char *message);

int main(int argc, char *argv[]) {
	WSADATA wsaData;
	int i;
	struct hostent *host;
	if (argc != 2) {
		printf("Usage : %s \n", argv[0]);
		exit(1);
	}
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
		ErrorHandling("WSAStartup() error!");

	host = gethostbyname(argv[1]);
	if (!host)
		ErrorHandling("gethost.....error!");

	printf("Official name: %s\n", host->h_name);
	for (i = 0; host->h_aliases[i]; i++)
		printf("Aliases %d: %s\n", i + 1, host->h_aliases[i]);
	printf("Address type : %s \n",(host->h_addrtype==AF_INET)?"AF_INET":"AF_INET6");

	for (i = 0; host->h_addr_list[i]; i++)
		printf("IP addr %d: %s \n",i+1,inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));

	WSACleanup();
	return 0;
}

void ErrorHandling(char *message) {
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}


gethostbyname_win.c 运行结果:
IP地址与域名之间的转换(Windows + Visual Studio 2015)_第1张图片



gethostbyaddr_win.c

#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include
#include
#include
#include

void ErrorHandling(char *message);
int main(int argc, char *argv[]) {
	WSADATA wsaData;
	int i;
	struct hostent *host;
	SOCKADDR_IN addr;
	if (argc != 2) {
		printf("Usage : %s  \n", argv[0]);
		exit(1);
	}

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
		ErrorHandling("WSAStartup() error!");

	memset(&addr, 0, sizeof(addr));
	addr.sin_addr.S_un.S_addr = inet_addr(argv[1]);
	host = gethostbyaddr((char*)&addr.sin_addr, 4, AF_INET);
	if (!host)
		ErrorHandling("gethost...error!");
	printf("Official name: %s \n", host->h_name);
	for (i = 0; host->h_aliases[i]; i++)
		printf("Aliases %d : %s \n", i + 1, host->h_aliases[i]);
	printf("Address type : %s \n", (host->h_addrtype == AF_INET) ? "AF_INET" : "AF_INET6");
	for (i = 0; host->h_addr_list[i]; i++)
		printf("IP addr %d: %s \n", i + 1, inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
	WSACleanup();
	return 0;
}

void ErrorHandling(char *message) {
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}

gethostbyaddr_win.c 运行结果:

IP地址与域名之间的转换(Windows + Visual Studio 2015)_第2张图片

你可能感兴趣的:(windows程序设计,TCP/IP,网络编程)