/* interface.c - Look up IP address to bind
 *
 * Copyright (C) 2005, 2007  Oskar Liljeblad
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <config.h>
#include <unistd.h>		/* POSIX */
#include <stdio.h>		/* C89 */
#include <string.h>		/* C89 */
#include <sys/socket.h>		/* POSIX */
#include <sys/ioctl.h>		/* ? */
#include <sys/param.h>		/* ? */
#include <net/if.h>		/* ? */
#include <netinet/in.h>		/* ? */
#include <arpa/inet.h>		/* ? */
#include "gmediaserver.h"

char *
get_ip_by_spec(char *spec)
{
    int fd;
    int badlen;
    struct ifreq ifr;
    struct in_addr addr;

    /* If the string badlen chars long, it's not a valid */
    /* IP address or interface name. An IPv4 address is */
    /* at max 15 characters long. */
    badlen = MAX(IF_NAMESIZE, 16);
    if (strnlen(spec, badlen) < badlen) {
	if (inet_aton(spec, &addr) > 0)
	    return spec;
	fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
	if (fd < 0)
    	    return NULL;	/* internal error */
	memset(&ifr, 0, sizeof(struct ifreq));
	strcpy(ifr.ifr_name, spec);
	ifr.ifr_addr.sa_family = AF_INET;
	if (ioctl(fd, SIOCGIFADDR, &ifr) >= 0) {
	    close(fd);
    	    return inet_ntoa(((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr);
	}
	close(fd);
    }

    return NULL;
}
