winpcap/libpcap 与原始套接字
我启动了一个需要使用网络级数据包(例如 IP/ICMP/UDP/TCP 数据包)的项目。
有两种主要方法来处理它:原始套接字和 Winpcap/libpcap。
我知道 pcap 在操作系统上安装驱动程序并允许程序员捕获和发送数据包。另一方面,原始套接字在 Windows 7 或更高版本中具有一些限制。
该项目需要向路由器发送一些 IP/ICMP/UDP/TCP 数据包并分析响应,例如 IP-Identifier
、TTL
,...。我还希望它能在 Linux 和 Windows 上运行。
您能列出这两种方法的比较吗?
I started a project that needs using network level packets such as IP/ICMP/UDP/TCP packets.
There is two main approach to handle it: Raw sockets and Winpcap/libpcap.
I know pcap installs a driver on OS and allows programmer to capture and send packets. On the other hand there is raw sockets which have some limitations in Windows 7 or above.
The project needs sending some IP/ICMP/UDP/TCP packets to a router and analyzes the responses, such as IP-Identifier
, TTL
, ... . Also I want it works in Linux and Windows.
Can you list a comparison about these two approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望代码是可移植的,那么您不能使用原始套接字 API(这在 Linux 和 Windows 上有很大不同)。 Winpcap 通常与 libpcap 兼容,并且考虑到 pcap API 的作用,它通常是合理的。
If you want the code to be portable, then you can't use the raw socket API (which is rather different on Linux and Windows). Winpcap is generally compatible with libpcap, and the pcap API is generally reasonable, considering what it's doing.
在你的情况下,原始套接字可以工作,但你必须做类似的事情
sock_raw_tcp = 套接字(AF_INET, SOCK_RAW, IPPROTO_TCP);
sock_raw_udp = 套接字(AF_INET, SOCK_RAW, IPPROTO_UDP);
sock_raw_icmp = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
您没有像 IP_PROTO_IP 这样的选项。现在,使用 RAW 套接字,您将仅获得 IP 标头 + 传输级标头,而不是以太网标头。因此,如果您只对应用层数据感兴趣并希望使用 IP 标头作为 Ipaddress & TTL 和端口号等传输头,然后就可以了。请记住,对于 TCP,您可能还必须进行校验和和重组。 UDP 还需要一些校验和。
然而,winpcap 为您解决了许多管理问题,因为它使用设备驱动程序连接 NIC 的数据链路层或第 2 层。在这里您还将获得一个以太网帧,并且不必打开不同类型的 RAW 套接字。您仍然必须像在网络层(第 3 层)上那样应用处理数据包的应用程序相关逻辑。
in your situation, RAW sockets will work but you have to do something like
sock_raw_tcp = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
sock_raw_udp = socket(AF_INET , SOCK_RAW , IPPROTO_UDP);
sock_raw_icmp = socket(AF_INET , SOCK_RAW , IPPROTO_ICMP);
You dont have an option like IP_PROTO_IP. Now, with RAW sockets, you will get only IP headers + transport level headers but not ethernet headers. So, if you are only interested in application layer data and want to use IP header for Ipaddress & TTL and transport header for port numbers etc, then its OK. Keep in mind that for TCP you might have to do check sums and reassembly also. Some checksums will also be required for UDP.
However, winpcap solves many management issues for you since it uses a device driver to connect your NIC's data link layer OR layer 2. Here you will also get an ethernet frame and wont have to open different types of RAW sockets. You still will have to apply the application related logic of dealing with packets as you would do on the network layer (Layer 3).