如何在 Python 中使用原始套接字?

编程入门 行业动态 更新时间:2024-10-27 07:28:33
本文介绍了如何在 Python 中使用原始套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个应用程序来测试处理损坏数据的网络驱动程序.并且我想到使用原始套接字发送这个数据,所以它不会被发送机器的 TCP-IP 堆栈纠正.

I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.

我仅在 Linux 上编写此应用程序.我有在系统调用中使用原始套接字的代码示例,但我真的希望尽可能保持我的测试动态,并用 Python 编写大部分(如果不是全部).

I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.

我在网上搜索了一些关于在 python 中使用原始套接字的解释和示例,但没有找到任何真正有启发性的东西.只是一个非常古老的代码示例,它演示了这个想法,但无论如何都行不通.

I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.

据我所知,Python 中的原始套接字用法在语义上与 UNIX 的原始套接字几乎相同,但没有定义数据包结构的 struct.

From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the structs that define the packets structure.

我想知道是否最好不要用 Python 编写测试的原始套接字部分,而是用带有系统调用的 C 语言编写,并从主 Python 代码中调用它?

推荐答案

你这样做:

首先禁用网卡的自动校验和:

First you disable your network card's automatic checksumming:

sudo ethtool -K eth1 tx off

然后从 python 2 发送你狡猾的框架(你必须自己转换到 Python 3):

And then send your dodgy frame from python 2 (You'll have to convert to Python 3 yourself):

#!/usr/bin/env python from socket import socket, AF_PACKET, SOCK_RAW s = socket(AF_PACKET, SOCK_RAW) s.bind(("eth1", 0)) # We're putting together an ethernet frame here, # but you could have anything you want instead # Have a look at the 'struct' module for more # flexible packing/unpacking of binary data # and 'binascii' for 32 bit CRC src_addr = "\x01\x02\x03\x04\x05\x06" dst_addr = "\x01\x02\x03\x04\x05\x06" payload = ("["*30)+"PAYLOAD"+("]"*30) checksum = "\x1a\x2b\x3c\x4d" ethertype = "\x08\x01" s.send(dst_addr+src_addr+ethertype+payload+checksum)

完成.

更多推荐

如何在 Python 中使用原始套接字?

本文发布于:2023-08-07 03:50:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316810.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!