發表文章

目前顯示的是 二月, 2009的文章

skb_copy v.s. skb_clone

skb_clone 和 skb_copy 有甚麼不一樣?

從字面上來看,差不多啊,但實際上就是有差,先來看看 Man 吧~

struct sk_buff * skb_clone (struct sk_buff * skb, int gfp_mask);

Duplicate an &sk_buff. The new one is not owned by a socket. Both copies share the same packet data but not structure. The new buffer has a reference count of 1. If the allocation fails the function returns NULL otherwise the new buffer is returned.

If this function is called from an interrupt gfp_mask must be GFP_ATOMIC.

struct sk_buff * skb_copy (const struct sk_buff * skb, int gfp_mask);

Make a copy of both an &sk_buff and its data. This is used when the caller wishes to modify the data and needs a private copy of the data to alter. Returns NULL on failure or the pointer to the buffer on success. The returned buffer has a reference count of 1.

As by-product this function converts non-linear &sk_buff to linear one, so that &sk_buff becomes completely private and caller is allowed to modify all the data of returned buffer. This means that this fu…

Netfilter 的 Hook 方式初探

圖片
Netfilier,Linux 核心裡面的封包處理子系統。這篇文章唯一時心血來潮,看了一小段 code 以後所作的整理。

kernel: 2.6.23.14

下圖是 Linux 核心的網路封包處理流程:



讓我們到 ip_rcv 這隻函式來看一下,ip_rcv 是處理 IP 封包的主要進入函式。

net/ipv4/ip_input.c:

/*
* Main IP Receive routine.
*/
int ip_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
....struct iphdr *iph;
....u32 len;

..../* When the interface is in promisc. mode, drop all the crap
....* that it receives, do not try to analyse it.
....*/
....if (skb->pkt_type == PACKET_OTHERHOST)
........goto drop;

....IP_INC_STATS_BH(IPSTATS_MIB_INRECEIVES);

....if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) {
........IP_INC_STATS_BH(IPSTATS_MIB_INDISCARDS);
........goto out;
....}

....if (!pskb_may_pull(skb, sizeof(struct iphdr)))
........goto inhdr_error;

....iph = ip_hdr(skb);

..../*
....* RFC1122: 3.1.2.2 MUST silently discard any IP frame that fails the checksum.
....*
....* Is the datagram acceptable?
....*
....* 1. Length at least the size of an ip header
...…

if ( x == 0 ) 和 if ( 0 == x ) 的差異

今天找到一本很不錯的書

C Programming FAQs: Frequently Asked Questions

看到其中一個問題,覺得很有意思,就把它記錄下來。

為什麼有人要寫 if ( 0 == x ) 而不是 if ( x == 0 )?

就程式語法上來看,這兩個是完全等義的,
而從一般人解讀的理解來說,if ( x == 0 ) 又比較好理解,
那位甚麼會有人故意寫成 if ( 0 == x )呢?

答案是:「防呆」

基本上寫程式的人大概都會犯上一個錯誤,== 和 = 的誤用。
新手可能是稿不清楚狀況,老手則可能是不小心犯下了這個錯誤(寫字都會有筆誤了)。
這個 Bug 是很難找出來的,因為對 Compiler 來說, x = 0 仍然可以當作判斷條件,
而且是成立的條件式。
這代表在測試的情況下非常有可能測不出來!!

可是如果寫成 if ( 0 == x ),當不小心寫錯的時候, if ( 0 = x )是可以被判斷出來的,
以 gcc 來說,錯誤信息如下:

Error: lvalue required as left operand of assignment

這樣程式設計師就可以很容易的發現這個問題而加以修正。

看來也許我要開始改變自己的寫法了~