使用gethostbyname()提取IP数据

Extracting IP Data using gethostbyname()

本文关键字:IP 数据 提取 gethostbyname 使用      更新时间:2023-10-16

现在,例如,如果我想找到某个主机的IP。我将使用gethostbyname()命令并将数据放在结构体host中。现在我想获得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: %sn", he->h_name);
    while (*he->h_aliases)
        printf("alias: %sn", *he->h_aliases++);
    while (*he->h_addr_list)
    {
        bcopy(*he->h_addr_list++, (char *) &a, sizeof(a));
        printf("address: %sn", inet_ntoa(a));
    }
 }
 else
    printf("error");
 return 0;
}
输出:

name: localhost
address: 127.0.0.1

你想这样做吗:

where Address是char*

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

.