/*

  This file is part of LFT.

  The LFT software provided in this Distribution is
  Copyright 2002 MainNerve, Inc.
 
  The full text of our legal notices is contained in the file called
  COPYING, included with this Distribution.

  ifname.c : ljd
  $Id: lft_ifname.c,v 1.3 2003/03/06 19:14:59 nils Exp $
*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#if !defined(linux) && !defined(__CYGWIN__)
#include <sys/sockio.h>
#endif
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <string.h>
#include <unistd.h>

#include "lft_ifname.h"

static int		sock = -1;

extern u_long
lft_getifaddr (const char *ifname)
{
	struct ifreq		ifr;

	/* Only do this once of course */
	if (sock < 0) {
		if ((sock = socket (AF_INET, SOCK_DGRAM, 0)) < 0) {
			perror ("socket");
			return -1;
		}
	}

	STRNCPY(ifr.ifr_name, (char*)ifname, IFNAMSIZ);

	if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) {
		perror("ioctl");
		return -1;
	}

	return ((struct sockaddr_in *)(&(ifr.ifr_addr)))->sin_addr.s_addr;
}

#ifdef	LFT_IFADDR_TESTING
extern int
main (int argc, char *argv[])
{
	struct in_addr		in;
	char			*addr;

	if (argc > 1)
		addr = strdup (argv[1]);
	else
		addr = strdup ("eth0");

	in.s_addr = lft_getifaddr (addr);
	if (in.s_addr == -1) {
		fprintf (stderr, "%s: Error reading ifname\n", addr);
		fflush (stderr);
		free(addr);
		exit (-1);
	}

	fprintf (stdout, "%s: %s\n", addr,
		inet_ntoa (in));
	fflush (stdout);
	free (addr);
	exit (0);
}

#endif /*LFT_IFNAME_TESTING*/
