site  contact  subhomenews

New 'getlocalip' utility

February 25, 2018 — BarryK

I am working on pup_event, and in 'pup_event_frontend_d' I have been exploring various ways of determining when a network connection is up or down.

An offshoot of that, is I wanted a very quick and efficient way to determine the local IP-address, that is, the IP address assigned to the computer, that other computers on a network will use to access this computer.

It can be found by the 'ifconfig', 'ip' and 'hostname' utilities, though I hasten to add, not the Busybox 'hostname'. The full 'hostname' has this option:

    -I, --all-ip-addresses all addresses for the host

...that is, a capital letter I, as in "India". In my case;

# hostname -I
192.168.0.2

I thought that it would be nice to have a specialized utility to return the local IP-address. I thought about parsing /proc/net/fib_trie, however, after a bit more research, settled on this simple C program:

#include <arpa/inet.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
struct ifaddrs *addrs, *tmp;
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);
exit(EXIT_SUCCESS);
}
Running it:
# getlocalip
lo: 127.0.0.1
eth0: 192.168.0.2
...bonus, it also shows the interface, in this case "eth0".

I got that code from here:

https://stackoverflow.com/questions/20800319/how-do-i-get-my-ip-address-in-c-on-linux

The source is in 'pup-tools-20180225.tar.gz':

http://distro.ibiblio.org/quirky/quirky6/sources/alphabetical/p/

BaCon Forum member 'airr' has converted it to BaCon code:

http://basic-converter.proboards.com/thread/999/example-find-local-ip-addresses

...great!

'getlocalip' will be in the next release of Easy and Quirky, in /usr/sbin.

Tags: easy, quirky