我正在理解这个gethostbyname()
功能。当时我找到了以下示例程序。
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *host, **names, **addrs;
struct hostent *hostinfo;
if(argc == 1)
{
char myname[256];
gethostname(myname, 255);
host = myname;
}
else
host = argv[1];
hostinfo = gethostbyname(host);
if(!hostinfo)
{
fprintf(stderr, "cannot get info for host: %s\n", host);
exit(1);
}
printf("results for host %s:\n", host);
printf("Name: %s\n", hostinfo -> h_name);
printf("Aliases:");
names = hostinfo -> h_aliases;
while(*names)
{
printf("%s", *names);
names++;
}
printf("\n");
if(hostinfo -> h_addrtype != AF_INET)
{
fprintf(stderr, "not an IP host!\n");
exit(1);
}
addrs = hostinfo -> h_addr_list;
while(*addrs)
{
printf(" %s", inet_ntoa(*(struct in_addr *)*addrs));
addrs++;
}
printf("\n");
exit(0);
}
现在我在我的系统上运行它。它工作正常。有两件事让我感到困惑:
- 在inet_ntoa函数中,我们有类型 case it like
inet_ntoa(*(struct in_addr *)*addrs)
。但是如果我们像inet_ntoa((struct in_addr) addrs)
.The 那样做类型案例,那么它就行不通了。我无法理解这背后的原因。还请解释一下这里进行了什么样的类型转换。 当我了解这个程序时。我也无法理解下面的 while 循环。
while(*addrs) { printf(" %s", inet_ntoa(*(struct in_addr *)*addrs)); 地址++;}
请解释一下。
假设有一个
char**test
指向字符串“india”。当我们做过类似的事情时test++
。它根据字符串大小递增。在这种情况下,它将增加 6(5 + 1(null char.))。为什么这样?