例如,如果我想找到某个主机的IP。我将使用gethostbyname()命令,并将数据放在struct中。现在我想得到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 */
};发布于 2015-09-23 11:32:13
下面是代码的示例。输出地址采用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发布于 2015-09-23 11:42:06
一定要做这样的事情:
地址为char*
struct in_addr IpAddress;
if(inet_aton(Address,&IpAddress))
{
return(ntohl((int)IpAddress.s_addr));
}。
https://stackoverflow.com/questions/32737083
复制相似问题