Linux下C/C++怎样通过主机名获得IP?

ysxin 2012-06-21 10:42:02
各位高手:
求getaddrbyhost()函数使用例子,求下面这个代码反过来的,通过主机名获得IP:

#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;
}
...全文
417 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2012-06-21
  • 打赏
  • 举报
回复
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。


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;
};


getaddrinfo一个函数全部搞定,给ip得Canonical name,给域名得IP。

但是别指望根据IP得到域名,这个功能是木有的,只能得到Canonical name和Alias,都是无用的。
pathuang68 2012-06-21
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
各位高手:
求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 <net……
[/Quote]

用gethostbyname这个函数就行了。

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧