Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get IP address programmatically on Debian based system?

I'm trying to retrieve the IP Address of the local machine in my program. The Operating System is Ubuntu 8.10. I tried using gethostname() and gethostbyname() to retrieve the IP Address. The answer I received is 127.0.1.1. I learned that it seems to be a Debian thing: The document linked here explained the idea.

The content of my /etc/hosts file is:

127.0.0.1 localhost
127.0.1.1 mymachine

In this case, is there any other way to programmatically (prefer C or C++) to get the IP Address without modifying the system file on the machine?

like image 474
gc . Avatar asked Jan 26 '26 21:01

gc .


2 Answers

Here's some quick and dirty code that demonstrates SIOCGIFCONF :

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    int sock, i;
    struct ifreq ifreqs[20];
    struct ifconf ic;

    ic.ifc_len = sizeof ifreqs;
    ic.ifc_req = ifreqs;

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket");
        exit(1);
    }

    if (ioctl(sock, SIOCGIFCONF, &ic) < 0) {
        perror("SIOCGIFCONF");
        exit(1);
    }

    for (i = 0; i < ic.ifc_len/sizeof(struct ifreq); ++i)
        printf("%s: %s\n", ifreqs[i].ifr_name,
                inet_ntoa(((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr));

    return 0;
}

I get the following output on my Linux machine.

lo: 127.0.0.1
br0: 192.168.0.42
dummy1: 10.0.0.2
like image 125
sigjuice Avatar answered Jan 29 '26 09:01

sigjuice


So, as per Ken's point:

ip addr show scope global | grep inet | cut -d' ' -f6 | cut -d/ -f1

Shame that when the Debian gods made the "ip" command they didn't think to add a simple command to get just the ip address.

like image 33
Martin Cleaver Avatar answered Jan 29 '26 11:01

Martin Cleaver