如何从 sk_buff 获取 IP 选项?

How to get IP Options from sk_buff?

我正在尝试使用 C++ 从 Linux 中的 IP 数据包中检索 IP 选项的数据。此代码发现数据包具有 IP 选项,但问题是我无法获取 IP 选项值。有没有办法获取 IP 选项的数据?

#include <linux/ip.h>

if(key->eth.type == htons(ETH_P_IP) && key->ip.tos != 0)
{
    struct iphdr *nh = (struct iphdr *)skb_network_header(skb);

    if(nh != NULL && nh->ihl * 4 > sizeof(struct iphdr))
    {
         // get IP options
    }
}

我找到了一种访问网络每个字节的方法 header。所以在典型的 header 之后有 IP 选项字节。在时间戳 IP 选项的情况下,第一个字节是 type,第二个字节是 length,第三个字节是 overflowflags。因此第四个字节是实际 IP 选项数据的开始。在我的解决方案中,我尝试将数据转换为 unsigned long int.

struct iphdr *nh = (struct iphdr *)skb_network_header(skb); // skb is socket buffer

unsigned int iphdr_size = sizeof(struct iphdr);

if(nh != NULL && nh->ihl * 4 > iphdr_size)
{
    u8 *opt;
    opt = (u_int8_t *)nh;

    unsigned long int optdata = 0;
    unsigned int i;

    for(i = iphdr_size + 4; i < nh->ihl * 4; i++)
    {
        optdata = (optdata << 8) | opt[i];
    }
    // Now we have data in optdata, do what you want to do
}

有一些有用的链接,例如:
IP & TCP Option Functions
Converting 8 byte char array into long