if(printk_ratelimit())
{
#define NIPQUAD(addr) \
((unsigned char *)&addr)[0],
\ ((unsigned char *)&addr)[1],
\ ((unsigned char *)&addr)[2],
\ ((unsigned char *)&addr)[3]
if((skb ->protocol) == htons(ETH_P_IP ))
{
struct iphdr *nh;
struct tcphdr *th;
nh = ip_hdr(skb);
//printk("src: %u.%u.%u.%u, dst: %u.%u.%u.%u\n", NIPQUAD(nh->saddr), NIPQUAD(nh->daddr));
if(nh->protocol == IPPROTO_TCP)
{
th = tcp_hdr(skb);
printk(" src: %u.%u.%u.%u, sport: %d dst: %u.%u.%u.%u dport: %d \n", NIPQUAD(nh->saddr), th->source, NIPQUAD(nh->daddr), th->dest);
}
}
}
最近编写内核代码,有发现一个新的内核打印ip地址的方法:
if (printk_ratelimit()) {
printk("%s fun: IP: %pI4\n", __func__, &iph->saddr);
}

本文介绍了在Linux内核代码中使用`printk_ratelimit()`结合宏`NIPQUAD()`来限制打印频率并优雅地显示IP地址的方法。当网络包为IP协议时,代码会提取并打印源和目标IP地址以及TCP信息,如端口号。此外,还展示了一个新的内核打印IP地址的简洁方式。
1479

被折叠的 条评论
为什么被折叠?



