Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

c - raw socket listener

This is a quick question for linux c programming raw sockets. If I wanted to just listen to any interface with a raw socket, must I actually bind to an ip address or interface to listen to traffic? From what I understand, I feel like I should be able to just call sock(); and then start recvfrom() traffic. Maybe I'm wrong, but I've seen some programs that don't use it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are right, the only thing you will need to do is call socket() and then recvfrom(). Nevertheless be aware of the fact that there are some limitations with listening using SOCK_RAW.

If you're not using raw sockets on a "send-and-forget" basis, you will be interested in reading the reply packet(s) for your raw packet(s). The decision logic for whether a packet will be delivered to a raw socket can be enumarated as such:

  1. TCP and UDP packets are never delivered to raw sockets, they are always handled by the kernel protocol stack.

  2. Copies of ICMP packets are delivered to a matching raw socket. For some of the ICMP types (ICMP echo request, ICMP timestamp request, mask request) the kernel, at the same time, may wish to do some processing and generate replies.

  3. All IGMP packets are delivered to raw sockets: e.g. OSPF packets.

  4. All other packets destined for protocols that are not processed by a kernel subsystem are delivered to raw sockets.

The fact that you're dealing with a protocol for which reply packets are delivered to your raw socket does not necessarily mean that you'll get the reply packet. For this you may also need to consider:

  1. setting the protocol accordingly while creating your socket via socket(2)system call. For instance, if you're sending an ICMP echo-request packet, and want to receive ICMP echo-reply, you can set the protocol argument (3rd argument) to IPPROTO_ICMP).

  2. setting the protocol argument in socket(2) to 0, so any protocol number in the received packet header will match.

  3. defining a local address for your socket (via e.g. bind(2)), so if the destination address matches the socket's local address, it'll be delivered to your application also.

For more details you can read e.g. this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...