【问题标题】:Extracting IP Data using gethostbyname()使用 gethostbyname() 提取 IP 数据
【发布时间】:2015-12-20 14:58:51
【问题描述】:

例如,如果我想查找某个主机的 IP。我会使用 gethostbyname() 命令并将他的数据放入 struct hostent 中。现在我想获取信息h_addr_list。所以我所做的是我开始打印地址,直到我得到一个空字符。现在我面临的问题是地址是 *char 格式,我想将它们更改为 IPv4 格式。我已经尝试了某些方法,但我一直遇到问题。

struct hostent 
{
    char *h_name;       /* Official domain name of host */
    char **h_aliases;   /* Null-terminated array of domain names */
    int h_addrtype;     /* Host address type (AF_INET) */
    int h_length;       /* Length of an address, in bytes */
    char **h_addr_list;     /* Null-terminated array of in_addr structs */
};

【问题讨论】:

  • 您是否想说您不知道如何将 IPv4 点分四元字符串转换为某种未指定的其他格式?你的代码示例在哪里?
  • “IPv4 格式”是什么意思?你的意思是你希望它们像“127.0.0.1”这样的带点四边形字符串吗?
  • ^像 127.0.0.1 一样的点四字符串。

标签: c++ networking dns


【解决方案1】:

这是代码示例。输出地址格式为digits.digits.digits.digits(包含点分)

#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>
struct hostent *he;
struct in_addr a;

int main ()
{
  he = gethostbyname ("localhost");
  if (he)
  {
    printf("name: %s\n", he->h_name);
    while (*he->h_aliases)
        printf("alias: %s\n", *he->h_aliases++);
    while (*he->h_addr_list)
    {
        bcopy(*he->h_addr_list++, (char *) &a, sizeof(a));
        printf("address: %s\n", inet_ntoa(a));
    }
 }
 else
    printf("error");
 return 0;
}

输出:

name: localhost
address: 127.0.0.1

【讨论】:

    【解决方案2】:

    确实想做这样的事情:

    地址是字符*

    struct in_addr IpAddress;
    if(inet_aton(Address,&IpAddress))
    {
        return(ntohl((int)IpAddress.s_addr));
    }
    

    .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      相关资源
      最近更新 更多