使用 gethostbyname() 提取 IP 数据

Extracting IP Data using gethostbyname()

现在举例来说,如果我想找到某个主机的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 */
};

这是代码示例。输出地址格式为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

是否想做这样的事情:

其中地址为 char*

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

.