三个示例:
1. example(TCP, UDP, RAW):int sock;struct ifreq ifr;sock = socket(AF_INET, SOCK_DGRAM, 0);memset(&ifr, 0x00, sizeof(ifr));strncpy(ifr.ifr_name, "eth0", IFNAMSIZE);setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, (char *)&ifr, sizeof(ifr));
2. example(PACKET):int sock;struct sockaddr_ll sl;struct ifreq ifr;sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IPV6));memset(&sl, 0x00, sizeof(sl));memset(&ifr, 0x00, sizeof(ifr));sl.sll_family = AF_PACKET;sl.sll_protocol = htons(ETH_P_IPV6);strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));ioctl(fd, SIOCGIFINDEX, &ifr);sl.sll_ifindex = ifr.ifr_ifindex;bind(fd, (struct sockaddr *)&sl, sizeof(sl));
3. example(PACKET):
int sock;struct sockaddr addr;sock = socket(PF_PACKET, SOCK_PACKET, ETH_P_IP);memset(&addr, 0x00, sizeof(addr));addr.sa_family = PF_PACKET;strncpy(addr.sa_data, "eth0", sizeof(addr.sa_data));bind(sock, &addr, sizeof(addr));
针对SO_BINDTODEVICE套接口选项,man(7)手册有如下说明: SO_BINDTODEVICE Bind this socket to a particular device like “eth0”, as specified in the passed interface name. If the name is an empty string or the option length is zero, the socket device binding is removed. The passed option is a variable-length null-terminated interface name string with the maximum size of IFNAMSIZ. If a socket is bound to an interface, only packets received from that particular interface are processed by the socket. Note that this only works for some socket types, particularly AF_INET sockets. It is not supported for packet sockets (use normal bind(8) there).参考信息: http://blog.chinaunix.net/u/270/showart_234383.html
