IP-address from sk_buff

前端 未结 6 1690
说谎
说谎 2021-02-02 17:43

I am writing a kernel module which registers a netfilter hook. I am trying to get the ip address of the caller by using the sk_buff->saddr member. Is there a way

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 18:15

    There are two macros defined in include/linux/kernel.h

    NIPQUAD for ipv4 addresses and NIP6 for ipv6 addresses.

    #define NIPQUAD(addr) \
        ((unsigned char *)&addr)[0], \
        ((unsigned char *)&addr)[1], \
        ((unsigned char *)&addr)[2], \
        ((unsigned char *)&addr)[3]
    
    #define NIP6(addr) \
        ntohs((addr).s6_addr16[0]), \
        ntohs((addr).s6_addr16[1]), \
        ntohs((addr).s6_addr16[2]), \
        ntohs((addr).s6_addr16[3]), \
        ntohs((addr).s6_addr16[4]), \
        ntohs((addr).s6_addr16[5]), \
        ntohs((addr).s6_addr16[6]), \
        ntohs((addr).s6_addr16[7])
    

    There are ample examples in the kernel sources that make use of these to print ip addresses in human-readable format. For instance:

    printk(KERN_DEBUG "Received packet from source address: %d.%d.%d.%d!\n",NIPQUAD(iph->saddr));
    

    Hope this helps.

提交回复
热议问题