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

linux获取主机名后用gethostbyname() 不能获取主机ip
我在虚拟机上用以下函数能获取主机ip的ip
char hostname[256];
if (gethostname(hostname, 256) == 0)
{
printf("localhost name:%s\n",hostname);
struct hostent* hostinfo = gethostbyname(hostname);


client_value->localip =(uint32_t)((struct in_addr*)hostinfo->h_addr_list[0])->s_addr;
printf("client_value->localip=%d\n",client_value->localip);
}
但是用交叉编译器编译后放到我arm板上就不行能获取主机名但是不是获取ip,提示段错误;
我在arm板的操作终端输入命令hostname -s会显示主机名 +unknown server error ,在虚拟机下输入该命令就只显示主机名
哪位高手帮忙指导指导arm板应该怎么设置啊

------解决方案--------------------
获取本机IP,你可以用:
char* getlocalhostip ()
{  
    int  MAXINTERFACES=16;
    char *ip=NULL;
    int fd, intrface, retn = 0;
    struct ifreq buf[MAXINTERFACES]; ///if.h
    struct ifconf ifc; ///if.h

    if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) //socket.h
    {
        ifc.ifc_len = sizeof buf;
        ifc.ifc_buf = (caddr_t) buf;
        if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) //ioctl.h
        {
            intrface = ifc.ifc_len / sizeof (struct ifreq);

            while (intrface-->0)
            {
                if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
                {
                    ip=(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));//types
                    break;
                }
            }
        }
        close (fd);
    }
    return ip;
}

gethostname() gethostbyname()在Linux不好用!