我正在尝试获取远程系统的主机名,但 gethostbyaddr 失败,错误号为 22,根据 errno.h 为 EINVAL 。我正在尝试获取 Windows 系统的主机名,但失败了,同样是对于Linux系统。但是相同的功能在Windows上运行良好。我已经浏览过thread根据他们的说法,必须存在反向 DNS 记录才能使该功能正常工作。是否有其他替代功能来获取远程系统名称?我已经发布了下面的代码,请告诉我获得相同代码的方法。
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(void)
{
struct hostent *hp;
in_addr_t ipaddr;
char Ipaddr[20];
printf("\n Enter the ip address : ");
scanf("%s",Ipaddr);
ipaddr=inet_addr(Ipaddr);
printf("Converted ip address : %zu",ipaddr);
printf("\n Hostname is : %s",hname);
hp=gethostbyaddr((void *)&ipaddr,4,AF_INET);
if(hp==NULL)
{
printf("\n The hostname could not be found ");
perror("gethostbyaddr"); // error printed as "gethostbyaddr: Success"
printf("Error Number : %d",errno); //error number is : 22 which is EINVAL as per the header file
return 0;
}
printf("\n The hostname by gethostbyaddr : %s",hp->h_name);
}
编辑
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
int dwRetval;
struct sockaddr_in saGNI;
char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
u_short port = 27015;
char Ip_Address[18];
// Validate the parameters
printf("enter the ip address : ");
scanf("%s",Ip_Address);
//-----------------------------------------
// Set up sockaddr_in structure which is passed
// to the getnameinfo function
saGNI.sin_family = AF_INET;
saGNI.sin_addr.s_addr = inet_addr(Ip_Address);
saGNI.sin_port = htons(port);
//-----------------------------------------
// Call getnameinfo
dwRetval = getnameinfo((struct sockaddr *) &saGNI,
sizeof (struct sockaddr),
hostname,
NI_MAXHOST, servInfo, NI_MAXSERV,NI_NOFQDN);
if (dwRetval != 0) {
perror("getnameinfo");
printf("getnameinfo returned herror = %d\n", errno);
return 1;
} else {
printf("getnameinfo returned hostname = %s\n", hostname);
return 0;
}
}
最佳答案
解析代码看起来没问题,但是错误报告部分是错误的。
至少在 Unix 上,gethostbyaddr()
不会设置errno
。如果出现错误,
设置了 h_errno
后,可以使用 herror()
打印文本错误消息:
if (hp == NULL) {
herror("Could not resolve address");
printf("Error Number : %d", h_errno);
return 0;
}
备注:将 IP 地址转换为主机名的更现代的接口(interface)是
getnameinfo()
。它适用于 IPv4 和 IPv6,并且在 Unix 和
Windows。
关于c - Gethostbyaddr 在 Linux 中失败,但在 Windows 机器上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331718/