【问题标题】:How to generate TCP/UDP packet using Python in Windows?如何在 Windows 中使用 Python 生成 TCP/UDP 数据包?
【发布时间】: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 那样简单。

  1. https://wiki.python.org/moin/TcpCommunication

  2. How To Generate Tcp,ip And Udp Packets In Python?

我在 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 数据包。

所以,我的问题是:

  1. 为什么是“你好,世界!”消息没有出现在 Wireshark (Follow TCP Stream) 中?

我在 Linux 中运行 echo "hello world" > /dev/tcp/127.0.0.1/1337 时可以看到该消息。

  1. 我在运行代码时也收到以下错误。

我搜索了错误,发现类似错误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>
  1. 这是在 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_STREAM API 更低的级别。
  • 谢谢@selbie,我也在远程服务器上试过这个。我可以看到数据包,但没有“hello world”消息。

标签: python windows sockets


【解决方案1】:

而不是这个:

s.send(MESSAGE)

这个:

b = s.send(MESSAGE.encode("utf8"))
s.send(b)

【讨论】:

  • 为什么要bytearray 而不是只使用encode?他不需要在任何地方改变字节或扩展数组,不是吗?
  • 谢谢@selbie。有用!我可以在远程服务器上创建的 Wireshark 和 nc 侦听器上看到该消息。不幸的是,我遇到了另一个错误。 ` 文件“C:\Python\Codes\tcp.py”,第 13 行,在 s.send(b) 类型错误:需要一个类似字节的对象,而不是 'int'` 完整代码在这里。 pastebin.com/nbBFftTtpastebin.com/nbBFftTt
【解决方案2】:

正如回溯所说,这是一个 TypeError:需要一个字节对象,而不是 str

所以,您可以在字符串上使用.encode() 来获取类似字节对象,然后使用.decode() 来取回字符串。

MESSAGE = 'Hello, World!'
encoded = str.encode(MESSAGE)     # b'Hello, World!'
decoded = encoded.decode()        # 'Hello, World!' 

这里,这个链接,你可能会发现它很有用。 Best way to convert string to bytes in Python 3?

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2012-01-02
    • 2015-02-05
    • 1970-01-01
    • 2012-02-09
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2012-10-20
    相关资源
    最近更新 更多