--- libaitio/src/bpf.c 2013/06/24 09:22:41 1.1.2.1 +++ libaitio/src/bpf.c 2013/06/24 11:09:55 1.1.2.2 @@ -1,3 +1,90 @@ #include "global.h" +/* + * io_get1stiface() - Get first interface of host + * + * @szIface = interface string buffer + * @iflen = size of interface buffer + * return: -1 error or 0 ok + */ +int +io_get1stiface(char *szIface, int iflen) +{ + struct ifaddrs *ifa; + + if (!szIface || !iflen) + return -1; + + getifaddrs(&ifa); + strlcpy(szIface, ifa->ifa_name, iflen); + freeifaddrs(ifa); + return 0; +} + +/* + * io_etherClose() - Close BPF interface + * + * @eth = bpf handle + * return: none + */ +void +io_etherClose(int eth) +{ + if (eth > STDERR_FILENO) + close(eth); +} + +/* + * io_etherOpen() - Open BPF interface to device + * + * @csIface = interface name + * @flags = open flags + * return: -1 error or >-1 bpf handle + */ +int +io_etherOpen(const char *csIface, int flags) +{ + int n = 1, eth = -1; + register int i; + char szStr[STRSIZ]; + struct ifreq ifr; + + for (i = 0; i < BPF_DEV_MAX; i++) { + memset(szStr, 0, sizeof szStr); + snprintf(szStr, sizeof szStr, "/dev/bpf%d", i); + eth = open(szStr, flags); + if (eth > STDERR_FILENO) + break; + } + if (eth < 3) { + LOGERR; + return -1; + } + + if (ioctl(eth, BIOCIMMEDIATE, &n) == -1) { + LOGERR; + close(eth); + return -1; + } + n = USHRT_MAX + 1; + if (ioctl(eth, BIOCSBLEN, &n) == -1) { + LOGERR; + close(eth); + return -1; + } + if (csIface) + strlcpy(szStr, csIface, sizeof szStr); + else if (io_get1stiface(szStr, sizeof szStr) == -1) { + close(eth); + return -1; + } + strlcpy(ifr.ifr_name, szStr, sizeof ifr.ifr_name); + if (ioctl(eth, BIOCSETIF, &ifr) == -1) { + LOGERR; + close(eth); + return -1; + } + + return eth; +}