发送数据包时如何设置iptables标记?

时间:2018-12-07 13:48:33

标签: c linux sockets networking iptables

Linux的iptable和iproute允许我们标记数据包并稍后匹配标记(fwmark),从而在配置路由和防火墙时具有极大的灵活性。

在通过普通套接字接口或特定的linux系统调用从C程序发送数据包时,是否有办法设置这些标记?

1 个答案:

答案 0 :(得分:0)

我在socket(7)手册页中找到了SO_MARK套接字选项:

   SO_MARK (since Linux 2.6.25)
          Set the mark for each packet sent through this socket (similar
          to the netfilter MARK target but socket-based).  Changing the
          mark can be used for mark-based routing without netfilter or
          for packet filtering.  Setting this option requires the
          CAP_NET_ADMIN capability.

并非如我最初要求的那样,每个数据包都适合我的目的。您可以使用setsockopt()进行设置:

int fwmark;
//fwmark = <some value>;
if(-1 == setsockopt(sockfd, SOL_SOCKET, SO_MARK, &fwmark, sizeof fwmark)) {
    perror("failed setting mark for socket packets");
}