Linux下C/C++怎样通过主机名获得IP?各位高手:求getaddrbyhost()函数使用例子,求下面这个代码反过来的,通过
Linux下C/C++怎样通过主机名获得IP?
各位高手:
求getaddrbyhost()函数使用例子,求下面这个代码反过来的,通过主机名获得IP:
- C/C++ code
#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;}[解决办法]
[解决办法]
struct hostent *gethostbyname(const char *name);
#include <sys/socket.h> /* for AF_INET */
struct hostent *gethostbyaddr(const void *addr,
socklen_t len, int type);
这些都是淘汰的函数了,只支持IPV4。
- C/C++ code
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_SOURCEDESCRIPTION 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; }; 