无法使用gethostbyname()获取本地IP [英] Can't obtain local IP using gethostbyname()

查看:50
本文介绍了无法使用gethostbyname()获取本地IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友使用以下代码段来检索主机在其局域网中的本地IP地址.

A friend used the following snippet of code to retrieve the local IP address of the host in his LAN.

int buffersize = 512;
char name[buffersize];

if(gethostname(name, buffersize) == -1){
    Exception excep("Failed to retrieve the name of the computer");
    excep.raise();
}

struct hostent *hp = gethostbyname(name);
if(hp == NULL){
    Exception excep("Failed to retrieve the IP address of the local host");
    excep.raise();
}

struct in_addr **addr_list = (struct in_addr **)hp->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++) {
    qDebug() << QString(inet_ntoa(*addr_list[i]));
}

它在Mac上似乎可以正常工作.他说,该阵列中的最后一个IP地址是他需要知道的.但是,我在Linux笔记本电脑上得到了这些值...

It appears to work fine on his Mac. He said that the last IP address in that array was the one he needed to know. However, I got these values on my Linux laptop...

127.0.0.2
192.168.5.1
1.2.3.0

这些看起来与我的适配器使用的值相似,但并不相同.以下是一些 ifconfig 数据:

These looks similar to the values used by my adapters, but not the same. Here's some ifconfig data:

eth0      Link encap:Ethernet  HWaddr 1C:C1:DE:91:54:1A  
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
wlan0     Link encap:Ethernet  HWaddr [bleep]
          inet addr:192.168.1.6  Bcast:192.168.1.255  Mask:255.255.255.0

似乎有些位被打乱了.我们在这里错过了重要的转变吗?

It appears that some of the bits were scrambled. Are we missing a crucial conversion here?

推荐答案

您建议的方法依赖于正确"的本地主机名和正确"配置的DNS系统.我将正确"用引号引起来,因为拥有未在DNS中注册的本地主机名对于除您的程序之外的所有用途都是完全有效的.

The method you suggest relies upon a "correct" local host name, and a "correctly" configured DNS system. I put "correct" in quotes, because having a local host name that is not registered with DNS is perfectly valid for every purpose, except your program.

如果您有一个已连接的套接字(或可以生成一个已连接的套接字),建议您使用 getsockname()查找 a 本地IP地址.(请注意:不是 the 本地IP地址-您可以有多个.)

If you have a connected socket (or can generate a connected socket), I suggest you use getsockname() to find a local IP address. (Note: not the local IP address -- you could have several.)

这是一个执行此操作的示例程序.显然,大多数情况是连接到 google.com 并打印结果.只有对 getsockname()的调用与您的问题密切相关.

Here is a sample program that does that. Obviously, most of it is connecting to google.com and printing the result. Only the call to getsockname() is germane to your question.

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

#include <stdio.h>
#include <errno.h>
#include <unistd.h>


int main(int ac, char **av) {
    addrinfo *res;
    if(getaddrinfo("google.com", "80", 0, &res)) {
        fprintf(stderr, "Can't lookup google.com\n");
        return 1;
    }

    bool connected = false;
    for(; res; res=res->ai_next) {
        int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if(fd < 0) {
            perror("socket");
            continue;
        }

       if( connect(fd, res->ai_addr, res->ai_addrlen) ) {
           perror("connect");
           close(fd);
           continue;
       }

       sockaddr_in me;
       socklen_t socklen = sizeof(me);
       if( getsockname(fd, (sockaddr*)&me, &socklen) ) {
           perror("getsockname");
           close(fd);
           continue;
       }

       if(socklen > sizeof(me)) {
           close(fd);
           continue;
       }

       char name[64];
       if(getnameinfo((sockaddr*)&me, socklen, name, sizeof name, 0, 0, NI_NUMERICHOST)) {
           fprintf(stderr, "getnameinfo failed\n");
           close(fd);
           continue;
        }
        printf("%s ->", name);

       if(getnameinfo(res->ai_addr, res->ai_addrlen, name, sizeof name, 0, 0, NI_NUMERICHOST)) {
           fprintf(stderr, "getnameinfo failed\n");
           close(fd);
           continue;
        }
        printf("%s\n", name);
        close(fd);
    }
}

这篇关于无法使用gethostbyname()获取本地IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆