0
votes

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.

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

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

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:

  1. 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.

  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?
2
Wireshark isn't likely going to read anything over the localhost (127.0.0.1) adapter.selbie
It's as simple to do in Python on linux as from the shell on linux: with open('/dev/tcp/127.0.0.1/31337, 'wb') as port31337: port31337.write(b'hello world').abarnert
Also, this doesn't "generate a TCP package", it writes to a TCP data stream, which could generate 1 packet or 5 packets or half a packet. Normally, in TCP, you don't worry about individual packets (when that's important, you usually want UDP instead); if you do, you need a lower level than the basic SOCK_STREAM API.abarnert
Thanks @selbie, I've also tried this on remote server. I can see the packet but "hello world" message is not there.user9013730

2 Answers

1
votes

Instead of this:

s.send(MESSAGE)

This:

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

As the traceback says, it is a TypeError: a bytes-object like is required, not a str

so, you can use .encode() on a string to get a bytes-object like and then .decode() to get back the string.

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?

Hope it helps.