Can't obtain local IP using gethostbyname()

前端 未结 2 1786
终归单人心
终归单人心 2021-01-22 06:22

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         


        
相关标签:
2条回答
  • 2021-01-22 06:51

    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.

    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.)

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-22 06:51

    If you really use Qt, you can use this code

    foreach (const QHostAddress& address, QNetworkInterface::allAddresses() ) {
            qDebug() << address.toString();
        }
    

    If you are not using Qt, you can study, how it is made there.

    0 讨论(0)
提交回复
热议问题