注意 struct ifreq 头文件如下: struct ifreq header file

#include <sys/ioctl.h>
#include <net/if.h>


route add ...
  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));

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).
Referenced from:


标签: linux, udp, socket