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

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;
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;

Running it:
# getlocalip
...bonus, it also shows the interface, in this case "eth0".

I got that code from here:

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

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


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

Tags: easy, quirky