我遇到了以下代码快照:
struct hostent *hp;
hp = my_gethostbyname(localhost);
if (hp == NULL) {
ls_syslog(LOG_ERR, I18N_FUNC_FAIL, fname, "my_gethostbyname()");
return -1;
}
strcpy(localhost, hp->h_name);
memcpy(&addr, hp->h_addr, hp->h_length);
Run Code Online (Sandbox Code Playgroud)
我对最后一个语句感到困惑,struct hostent的声明是这样的:
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
};
Run Code Online (Sandbox Code Playgroud)
它没有名为"h_addr"的字段,但代码确实可以编译,任何人都可以告诉我为什么?谢谢.
我有以下代码来获取主机名和IP地址,
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h> /* This is the header file needed for gethostbyname() */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[])
{
struct hostent *he;
if (argc!=2){
printf("Usage: %s <hostname>\n",argv[0]);
exit(-1);
}
if ((he=gethostbyname(argv[1]))==NULL){
printf("gethostbyname() error\n");
exit(-1);
}
printf("Hostname : %s\n",he->h_name); /* prints the hostname */
printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr))); /* prints IP address */
}
Run Code Online (Sandbox Code Playgroud)
但是我在编译期间收到警告:
$cc host.c -o host
host.c: In function ‘main’:
host.c:24: warning: format ‘%s’ expects type ‘char …Run Code Online (Sandbox Code Playgroud)