日期:2014-05-16  浏览次数:20911 次

linux 下c代码实现通过ip得到主机名,出现问题

/******************************************
根据ip得到主机名hostname
******************************************/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    struct sockaddr_in addr;
    struct hostent *host;
    char ipaddr[40];
    printf("请输入IP\n");
    scanf("%s",ipaddr);
    getchar();
    if(inet_aton(ipaddr,&addr.sin_addr)!=0)
    {
        host=gethostbyaddr((char *)&addr.sin_addr,4,AF_INET);
       
    }
    if(host==NULL)
    {
        fprintf(stderr,"NO address information of host %s\n",ipaddr);
        exit(1);
    }
   
    printf("HostName :%s\n",host->h_name);
 //   printf("IP Address :%s\n",ipaddr);
    return 0;
   


编译运行得到的结果都是这个样子:
请输入IP
192.168.2.111
HostName :localhost

为什么得到的结果全是localhost啊。。。我其他的程序同理也这样。。。。



------解决方案--------------------
你的IP 不都是你自己主机的IP吗,肯定是得到的是localhost 了!
------解决方案--------------------
看看你的/etc/hosts里的内容是怎么样的