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 运行结果:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值