Search code examples
pythonpython-3.xsocketsethernetraw-ethernet

Python layer 2 Ethernet frames --> Receiving data


I'm creating some layer 2 frames for doing an automation bus simulation with Python 3. Actually the data will be send without problems. The communication partner returns the data back to my python script. I'm starting the script as root and the receiving is done. After I restart the script, I'm not able to receive data again. I have to start it a again… Now I'm searching for the reason.

Actual conditions:

  • VirtualBox with Ubuntu 18 --> 4.18.0-17-generic
  • USB 2 Network Interface directly connected to the virtual machine (Adapter is: enx0050b611bbf0).

Python:

s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind(('enx0050b611bbf0', 3))
s.send(packet)
response = s.recv(1024)
print('Recv: %s' % bytes_to_hex_str(response))
print('Recv length: %i' % len(response))
s.close()

The packet: It is a byte array:

0xff 0xff 0xff 0xff 0xff 0xff 0xde 0xad 0xbe 0xef 0x12 0x34 0x88 0xcd 0x20 0x00 0xa9 0xd7 0xdb 0x8f 0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00

Problem: It works only one time. After starting the script a second time, the s.recv() is blocking the script. I have to stop it manually and restart it. Then it is working one time…

Is someone able to explain me the problem?


Solution

  • I put everything in a multithreading environment. One for sending and one for receiving. Now it is working. The reason was a problem with cyclic sending of the Ethernet frames. Thank's for the help...