简体   繁体   English

如何在Windows中使用Python生成TCP / UDP数据包?

[英]How to generate TCP/UDP packet using Python in Windows?

In Linux, I can generate a TCP/UDP packet with the following command. 在Linux中,我可以使用以下命令生成TCP / UDP数据包。

echo "hello world" > /dev/tcp/127.0.0.1/1337
echo "hello world" > /dev/udp/127.0.0.1/31337

I've been searching a similar way to do it in Python, but it's not as simple as Linux. 我一直在寻找在Python中执行此操作的类似方法,但它并不像Linux那样简单。

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

  2. How To Generate Tcp,ip And Udp Packets In Python? 如何在Python中生成Tcp,ip和Udp数据包?

I'm using Python 3.5.1 in Windows and try the following code. 我在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)

I've also performed a packet capture to see this packet and was able to see TCP 3 way handshake followed by FIN packet. 我还执行了数据包捕获以查看此数据包,并能够看到TCP 3方式握手以及FIN数据包。

So, my questions are: 因此,我的问题是:

  1. Why "Hello, World!" 为什么是“你好,世界!” message did not appear in Wireshark (Follow TCP Stream)? 消息未出现在Wireshark中(关注TCP流)?

I can see the message when I run echo "hello world" > /dev/tcp/127.0.0.1/1337 in Linux. 在Linux中运行echo "hello world" > /dev/tcp/127.0.0.1/1337时,我可以看到该消息。

  1. I also get the following error when running the code. 运行代码时,我还会收到以下错误。

I googled the error and found similar error here , but the code is different. 我搜索了该错误,并在此处发现了类似的错误,但是代码不同。

Please let me know what's wrong with the code and how to fix it. 请让我知道代码有什么问题以及如何解决。

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. Is this the simplest way to generate TCP packet in Python? 这是在Python中生成TCP数据包的最简单方法吗?

Instead of this: 代替这个:

s.send(MESSAGE)

This: 这个:

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

As the traceback says, it is a TypeError: a bytes-object like is required, not a str 正如回溯所说,这是一个TypeError:像这样的byte-object是必需的,而不是str

so, you can use .encode() on a string to get a bytes-object like and then .decode() to get back the string. 因此,您可以在字符串上使用.encode()来获取类似字节的对象,然后使用.decode()来获取字符串。

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

here, this link, you might find it useful. 在这里,此链接可能会很有用。 Best way to convert string to bytes in Python 3? 在Python 3中将字符串转换为字节的最佳方法?

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM