SPUG: Get the local IP address?

Brian Hatch bri at ifokr.org
Sat Jul 23 08:11:45 PDT 2005

> I know. I was just hoping for a simpler solution.
> Regex is so easy to get wrong...

You could convert the following C code to perl, or just
use it via $ipaddr=`ipaddr $INTERFACENAME`.

It binds a socket to the interface and then uses that
socket to get the address info for it.  Should work on
any linux, regardless of distro or version of ifconfig,
because it doesn't parse anything.  Haven't tried it on
*BSD or others, but should work in theory.

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

int main( int argc, char **argv ) {
	struct ifconf ifc;
	char *interface;
	char buff[BUFSIZ];
	int sock, iface, num;
	struct ifreq *ifr=NULL;
	if ( argc == 1 ) {
		interface = "eth0";
	} else if ( argc == 2 ) {
		interface = argv[1];
	} else {
		fprintf(stderr, "Usage: %s [interface_name]\n", argv[0]);
		fprintf(stderr, "Usage: %s [interface_name]\n", argv[0]);
		fprintf(stderr, "e.g. %s eth0:1\n", argv[0]);
		fprintf(stderr, "if no interface specified, eth0 assumed.\n");

	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	ifc.ifc_len = sizeof(buff);
	ifc.ifc_buf = buff;

	ioctl(sock, SIOCGIFCONF, &ifc);
	ifr = ifc.ifc_req;

	num = ifc.ifc_len / sizeof(struct ifreq);

	/* Loop through all interfaces. */
	for ( ; iface<num ; iface++) {
		if (ioctl(sock, SIOCGIFADDR, &ifr[iface]) == 0 &&
			strcmp(ifr[iface].ifr_name, interface) == 0) {
				printf("%s\n", inet_ntoa(
				(*(struct sockaddr_in *)&ifr[iface].ifr_addr).sin_addr));

Brian Hatch                  $ cd ~bri
   Systems and               $ chown bree heart
   Security Engineer

Every message PGP signed
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.pm.org/pipermail/spug-list/attachments/20050723/8a01228c/attachment-0001.bin

More information about the spug-list mailing list