/* Lookup a route for a specified destination */ #include #include #include #include #include #include #include #include #include #include struct in_addr *lookup_iface(char *); struct my_ifreq { char ifrn_name[IFNAMSIZ]; /* Interface name, e.g. "en0". */ struct sockaddr_in ifru_addr; } ifreq; int main(int argc, char **argv) { struct hostent *remote_host; unsigned int remote_ip; FILE *PROC; char line[512]; if (argc > 1) { remote_host = gethostbyname(argv[1]); memcpy((char *) &remote_ip, remote_host->h_addr_list[0],sizeof(remote_host->h_addr_list[0])); } else { fprintf(stderr, "Usage: %s remote_ip\n",argv[0]); exit(1); } PROC = fopen("/proc/net/route","r"); /* First line contains headers */ fgets(line,sizeof(line),PROC); while (!feof(PROC)) { char iface[8]; unsigned int dest, gateway, mask; int i,field = 0; char *fields[10]; fgets(line,sizeof(line),PROC); for (i=0;i 9) /* Don't need any more fields */ /* Why 9 and not 8? Well, because during the 9th loop, we figure the end of the 8th field */ i = sizeof(line); else { *byteoffset = '\0'; i = byteoffset - line; } } sscanf(fields[0],"%s",iface); sscanf(fields[1],"%x",&dest); sscanf(fields[2],"%x",&gateway); sscanf(fields[7],"%x",&mask); if (((remote_ip & mask) ^ dest) == 0) { struct in_addr *temp; printf("Interface is %s\n",iface); temp = lookup_iface(iface); printf("IP Address is %s\n",inet_ntoa(*temp)); exit(0); } } fclose(PROC); exit(0); } struct in_addr *lookup_iface(char *iface) { int mysock; strncpy(ifreq.ifrn_name,iface,sizeof(ifreq.ifrn_name)); mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP); ioctl(mysock,SIOCGIFADDR,&ifreq); close(mysock); return( (struct in_addr *) &ifreq.ifru_addr.sin_addr ); }