0
点赞
收藏
分享

微信扫一扫

下载最新VMware,社区版本(免费)

爱情锦囊 03-24 21:01 阅读 1

利用域名获取IP

gethostbyname()

(该函数在Linux手册中已经被标注[[deprecated]],不建议再使用。)

#include <netdb.h>

struct hostent* gethostbyname(const char* hostname);

入参是域名字符串,返回值中存储了对应的IP地址。

struct hostent
{
  char *h_name;			/* Official name of host.  */
  char **h_aliases;		/* Alias list.  */
  int h_addrtype;		/* Host address type.  */
  int h_length;			/* Length of address.  */
  char **h_addr_list;	/* List of addresses from name server.  */
}

除了返回IP信息外,还带有其他信息。
域名转IP只需要关注h_addr_list

  • h_name
    存有官方域名。官方域名代表某一主页,但实际上,一些著名公司的域名并未用官方域名注册。
  • h_aliases
    可以通过多个域名访问同一主页。同一IP可以绑定多个域名,因此,除官方域名外还可指定其他域名。这些信息存在h_aliases中。
  • h_addrtype
    gethostname()支持IPV4和IPV6。通过此变量获取保存在h_addr_list的IP地址信息,如果是IPV4,则该变量存有AF_INET
  • h_length
    保存的IP地址长度。IPV4是4字节,IPV6是16字节。
  • h_addr_list
    以点分十进制保存域名对应的IP地址。

Example

#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main(int argc, char **argv)
{
    int i;
    struct hostent *host;

    if (argc != 2)
    {
        printf("Usage: %s <addr>\n", argv[0]);
        return 0;
    }

    host = gethostbyname(argv[1]);
    if (host == NULL)
    {
        perror("error()");
        return -1;
    }

    printf("Official name: %s\n", host->h_name);

    for (int 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( int 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]));
    }
}
举报

相关推荐

0 条评论