Search code examples
clinuxsocketsnetwork-programmingiptables

How to set iptables mark when sending a packet?


Linux's iptable and iproute allows us to mark packets and matches the mark later (fwmark), allowing for great flexibility in configuring routes and firewalls.

Is there a way to set those marks while sending the packet from a C program, either via ordinary sockets interface or via specific linux system calls?


Solution

  • I found the SO_MARK socket option in socket(7) man page:

       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.
    

    It is not per packet, as I originally asked, suits my purpose. You can set it with setsockopt():

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