【发布时间】:2018-08-21 05:32:30
【问题描述】:
在 Linux 中,我可以使用以下命令生成 TCP/UDP 数据包。
echo "hello world" > /dev/tcp/127.0.0.1/1337
echo "hello world" > /dev/udp/127.0.0.1/31337
我一直在寻找在 Python 中类似的方法,但它不像 Linux 那样简单。
我在 Windows 中使用 Python 3.5.1 并尝试以下代码。
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 1337
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print ("received data:", data)
我还执行了数据包捕获以查看此数据包,并且能够看到 TCP 3 方式握手,然后是 FIN 数据包。
所以,我的问题是:
- 为什么是“你好,世界!”消息没有出现在 Wireshark (Follow TCP Stream) 中?
我在 Linux 中运行 echo "hello world" > /dev/tcp/127.0.0.1/1337 时可以看到该消息。
- 我在运行代码时也收到以下错误。
我搜索了错误,发现类似错误here,但代码不同。
请让我知道代码有什么问题以及如何修复它。
C:\Python\Codes>tcp.py
Traceback (most recent call last):
File "C:\Python\Codes\tcp.py", line 12, in <module>
s.send(MESSAGE)
TypeError: a bytes-like object is required, not 'str'
C:\Python\Codes>
- 这是在 Python 中生成 TCP 数据包的最简单方法吗?
【问题讨论】:
-
Wireshark 不太可能通过 localhost (127.0.0.1) 适配器读取任何内容。
-
在 Python on linux 中与在 linux 上的 shell 中一样简单:
with open('/dev/tcp/127.0.0.1/31337, 'wb') as port31337: port31337.write(b'hello world'). -
另外,这不会“生成 TCP 数据包”,它写入 TCP 数据流,可能会生成 1 个数据包或 5 个数据包或半个数据包。通常,在 TCP 中,您不必担心单个数据包(当这很重要时,您通常需要 UDP 代替);如果这样做,则需要比基本的
SOCK_STREAMAPI 更低的级别。 -
谢谢@selbie,我也在远程服务器上试过这个。我可以看到数据包,但没有“hello world”消息。