1. 程式人生 > >IP地址與域名之間的轉換(Windows + Visual Studio 2015)

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<stdio.h>
#include<stdlib.h>
#include<WinSock2.h>

void ErrorHandling(char *message);

int main(int argc, char *argv[]) {
	WSADATA wsaData;
	int i;
	struct hostent *host;
	if (argc != 2) {
		printf("Usage : %s <addr>\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 執行結果:

gethostbyaddr_win.c

#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<WinSock2.h>

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 <IP> \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 執行結果: