/*
 *      idlescan
 *      Copyright (C) 1999 LiquidK <liquidk@superbofh.org>
 *
 */


#include "global.h"
#include <netinet/if_ether.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>


#define PROC_NET_ROUTE "/proc/net/route"

int get_ip_by_iface(char *dev)
{
    int f;
    struct ifreq ifr;
    struct sockaddr_in sa;

    if ((f = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
	perror("socket");
	return -1;
    }
    /*
    strncpy(ifr.ifr_name, dev, sizeof(ifr.ifr_name));
    if (ioctl(f, SIOCGIFFLAGS, (char *)&ifr) < 0){
	perror("ioctl(SIOCGIFFLAGS)");
	exit(-1);
    }
    */
    strncpy(ifr.ifr_name, dev, sizeof(ifr.ifr_name));
    if ( ioctl(f, SIOCGIFADDR, (char*)&ifr) == -1) {
	perror("ioctl(SIOCGIFADDR)");
	exit(-1);
    }
    memcpy(&sa, &ifr.ifr_ifru.ifru_addr, sizeof(struct sockaddr_in));
    

    return sa.sin_addr.s_addr;
}


char *get_iface_by_dest(int dest)
{
    FILE *f;
    char buffer[1024];
    char *iface_s;
    char *dest_s;
    char *netmask_s;
    int route_dest;
    int route_netmask;
    

    if(!(f = fopen( PROC_NET_ROUTE, "r"))) {
	perror("fopen /proc/net/route:");
	exit(-1);
    }

    if(!fgets(buffer, sizeof(buffer), f) )
	return NULL;
    
    while(fgets(buffer, sizeof(buffer), f) ) {
	iface_s = strtok(buffer, "\t");
	dest_s = strtok(NULL,"\t");
	strtok(NULL,"\t");
	strtok(NULL,"\t");
	strtok(NULL,"\t");
	strtok(NULL,"\t");
	strtok(NULL,"\t");
	netmask_s = strtok(NULL,"\t");

        route_dest = strtoul(dest_s, NULL, 16); 
        route_netmask = strtoul(netmask_s, NULL, 16); 

	if( (route_netmask & dest) == route_dest )
	    return strdup(iface_s);
    }
    return NULL;
}
