#if !defined(LINUX_VERSION_CODE)
#include <linux/version.h>
#endif

#if LINUX_VERSION_CODE < 0x20000
#error "Linux kernel < 2.0 not supported. Sorry."
#endif

#include <sys/types.h>

#include <features.h>		/* for the glibc version number */
#if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1
#include <netpacket/packet.h>	/* struct sockaddr_ll */
#else
#include <asm/types.h>
#include <linux/if_packet.h>	/* struct sockaddr_ll */
#endif

#include <net/if.h>		/* struct ifreq */
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>

int bind_interface(char *interface_name)
{
#if LINUX_VERSION_CODE < 0x20100
	struct sockaddr sa;
#else
	struct ifreq ifr;
	struct sockaddr_ll sa;
#endif
	int sock, ret;

	sock = socket(PF_PACKET, SOCK_STREAM, 0);
	if (sock == -1)
		return -errno;

	memset(&sa, 0, sizeof(sa));

#if LINUX_VERSION_CODE < 0x20100
	sa.sa_family = AF_INET;
	memcpy(sa.sa_data, interface_name, strlen(interface_name));
#else
	memset(&ifr, 0, sizeof(struct ifreq));
	memcpy(ifr.ifr_name, interface_name, strlen(interface_name));

	ret = ioctl(sock, SIOCGIFINDEX, &ifr);
	if (ret == -1)
		return -errno;

	sa.sll_family = AF_INET;
	sa.sll_ifindex = ifr.ifr_ifindex;
#endif

	ret = bind(sock, (struct sockaddr *)&sa, sizeof(sa));
	if (ret < 0)
		return -errno;

	return sock;
}


