In Linux, I can generate a TCP/UDP packet with the following command.
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.
I'm using Python 3.5.1 in Windows and try the following code.
#!/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.
So, my questions are:
- Why "Hello, World!" message did not appear in Wireshark (Follow TCP Stream)?
I can see the message when I run echo "hello world" > /dev/tcp/127.0.0.1/1337
in Linux.
- 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>
- Is this the simplest way to generate TCP packet in Python?
with open('/dev/tcp/127.0.0.1/31337, 'wb') as port31337: port31337.write(b'hello world')
. – abarnertSOCK_STREAM
API. – abarnert