9

How could I get my IP address (preferably in 192.168.0.1 format)?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jelly
  • 4,522
  • 6
  • 26
  • 42

2 Answers2

15

This example code lists both the interface name (e.g. lo or eth0) together with the currently assigned IP address, for all the IPv4 network interfaces that exist on your computer:

getifaddrs(&addrs);
tmp = addrs;

while (tmp) 
{
    if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET)
    {
        struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;
        printf("%s: %s\n", tmp->ifa_name, inet_ntoa(pAddr->sin_addr));
    }

    tmp = tmp->ifa_next;
}

freeifaddrs(addrs);
brm
  • 3,706
  • 1
  • 14
  • 14
  • 1
    uClibc does not contain getifaddrs until very crecently. Do you know any other method which could be used on embedded devices? – Marki555 Dec 29 '14 at 00:44
7

For Linux:

To get all interfaces local to the machine use getifaddrs().

There is an example at the end of the page linked above.

alk
  • 69,737
  • 10
  • 105
  • 255