64,654
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char **argv)
{
struct hostent *ip;
unsigned long hostname;
if (argc != 2)
{
printf("Need to specify an IP address.\n");
return -1;
}
if ((hostname = inet_addr(argv[1])) == -1)
{
printf("Could not find %s\n", argv[1]);
return -1;
}
else
{
printf("hostname : %ld\n", hostname);
}
if ((ip = gethostbyaddr((char *)&hostname, sizeof(long), AF_INET)) != NULL)
printf("%s is %s\n", argv[1], ip->h_name);
else
printf("Could not resolve %s\n", argv[1]);
return 0;
}
SYNOPSIS
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints,
struct addrinfo **res);
void freeaddrinfo(struct addrinfo *res);
const char *gai_strerror(int errcode);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
getaddrinfo(), freeaddrinfo(), gai_strerror():
_POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
DESCRIPTION
Given node and service, which identify an Internet host and a service, getaddrinfo() returns one or more addrinfo structures, each of which contains an
Internet address that can be specified in a call to bind(2) or connect(2). The getaddrinfo() function combines the functionality provided by the get-
servbyname(3) and getservbyport(3) functions into a single interface, but unlike the latter functions, getaddrinfo() is reentrant and allows programs to
eliminate IPv4-versus-IPv6 dependencies.
The addrinfo structure used by getaddrinfo() contains the following fields:
struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
struct sockaddr *ai_addr;
char *ai_canonname;
struct addrinfo *ai_next;
};