gethostbyaddr根据ip地址获取主机完整信息
函数原型:
#include <netdb.h>
#include <sys/socket.h> /* for AF_INET */
struct hostent *gethostbyaddr(const void *addr,socklen_t len, int type);
参数:
- const void *addr:参数addr不是void*类型, 而是一个真正指向含有IPv4或IPv6地址的结构in_addr或in6_addr;
- socklen_t len:第一个参数的结构大小,对于 IPv4地址为4,对于IPv6地址为16;
- int family:AF_INET或AF_INET6;
struct hostent结构体
struct hostent {
char * h_name; / *主机的正式名称* /
char ** h_aliases; / *主机的别名,一个主机可以有多个别名* /
int h_addrtype; / *主机地址类型:IPV4-AF_INET* /
int h_length; / *主机地址字节长度,对于IPv4是四字节,即32位* /
char ** h_addr_list; / *地址列表* /
}
示例:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
int main(int argc, char **argv)
{
char *ptr, **pptr;
struct in_addr addr;
struct hostent *phost;
char str[32] = {0};
ptr = argc < 2 ? "180.101.49.11" : argv[1];
printf("ip:%s\n", ptr);
if (inet_pton(AF_INET, ptr, &addr) <= 0) {
printf("inet_pton error:%s\n", strerror(errno));
return -1;
}
phost = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);
if (phost == NULL) {
printf("gethostbyaddr error:%s\n", strerror(h_errno));
return -1;
}
printf("official hostname:%s\n", phost->h_name); //主机规范名
return 0;
}
参考资料
https://blog.csdn.net/xiexingshishu/article/details/39803235
https://blog.csdn.net/fhbystudy/article/details/10022257