int inet_aton(const char *cp, struct in_addr *inp);
将形如“192.168.1.1"类型的点分十进制ip转换成二进制,并存放在struct in_addr中
192 = 0xc0
168 = 0xa8
1 = 0x01
因此转换后的值为0xc0a811
char *inet_ntoa(struct in_addr in);
将二进制的ip转成点分十进制形式,转换结果作为返回值
struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type);
将32位的二进制ip转换成一个结构体指针
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 from name server. */
#ifdef __USE_MISC
# define h_addr h_addr_list[0] /* Address, for backward compatibility.*/
#endif
};
typedef uint32_t in_addr_t;
struct in_addr
{
in_addr_t s_addr;
};
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
int main(int argc, char** argv)
{
struct in_addr addr;
struct hostent *host;
char ** var;
if(argc < 2)
{
printf("usage: %s | ip\n", *argv);
exit(1);
}
argv++;
for(; *argv!=NULL; argv++)
{
if(inet_aton(*argv, &addr) != 0)
{
host = gethostbyaddr(&addr, 4, AF_INET);
printf("ip address: %s\n", *argv);
}
if(host == NULL)
{
fprintf(stderr, "no ip address: %s\n", argv[1]);
continue;
}
else
{
printf("host name: %s\n", host->h_name);
for(var=host->h_addr_list; *var!=NULL; var++)
{
printf("inet_ntoa ip address: %s\n", inet_ntoa(*(struct in_addr*)(*var)));
}
}
}
return 0;
}
输出结果