您的位置:首页 > 运维架构 > Linux

linux获取主机名后用gethostbyname() 不能获取主机ip,该怎么处理

2013-05-08 09:15 246 查看
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不好用!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: