实验要求
给出域名,调用WindowsAPI,解析域名,返回其IPV4地址。
Code
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib")
int main(int argc, char **argv)
{
//-----------------------------------------
// Declare and initialize variables
WSADATA wsaData;
int iResult;
DWORD dwError;
int i = 0;
struct hostent *remoteHost;
char *host_name;
struct in_addr addr;
char **pAlias;
// Validate the parameters
if (argc != 2) {
printf("usage: %s hostname
", argv[0]);
printf(" to return the IP addresses for the host
");
printf(" %s www.contoso.com
", argv[0]);
printf(" or
");
printf(" %s IPv4string
", argv[0]);
printf(" to return an IPv4 binary address for an IPv4string
");
printf(" %s 127.0.0.1
", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d
", iResult);
return 1;
}
host_name = argv[1];
printf("Calling gethostbyname with %s
", host_name);
remoteHost = gethostbyname(host_name);
if (remoteHost == NULL) {
dwError = WSAGetLastError();
if (dwError != 0) {
if (dwError == WSAHOST_NOT_FOUND) {
printf("Host not found
");
return 1;
} else if (dwError == WSANO_DATA) {
printf("No data record found
");
return 1;
} else {
printf("Function failed with error: %ld
", dwError);
return 1;
}
}
} else {
printf("Function returned:
");
printf(" Official name: %s
", remoteHost->h_name);
for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
printf(" Alternate name #%d: %s
", ++i, *pAlias);
}
printf(" Address type: ");
switch (remoteHost->h_addrtype) {
case AF_INET:
printf("AF_INET
");
break;
case AF_NETBIOS:
printf("AF_NETBIOS
");
break;
default:
printf(" %d
", remoteHost->h_addrtype);
break;
}
printf(" Address length: %d
", remoteHost->h_length);
i = 0;
if (remoteHost->h_addrtype == AF_INET)
{
while (remoteHost->h_addr_list[i] != 0) {
addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
printf(" IP Address #%d: %s
", i, inet_ntoa(addr));
}
}
else if (remoteHost->h_addrtype == AF_NETBIOS)
{
printf("NETBIOS address was returned
");
}
}
return 0;
}
程序说明
编译:gcc -fexec-charset=GBK gethostbyname.c -o gethostbyname -lws2_32
执行
- 不带参数
gethostbyname
- 带参数
gethostbyname www.baidu.com
实验截图