5

I am new to Python and trying to send a byte array as a raw packet using a socket. My IP is 192.168.0.116 and the device I am sending this to is 192.168.0.64. This client device is a microcontroller based unit which is executing my code to simply sniff the Ethernet packets and check for a particular pattern. I am using UDP packets and tried the client side firmware by using 'Ostinato' in my PC to send a raw UDP packet. I am using Wireshark to monitor the network packet flow. The client seems to work fine with packets sent by Ostinato.

However when I try to send the same packet with Python (using raw packets as follows), it doesn't seem to spit out the bytes as I cant see anything on Wireshark nor the client get any data. But the return value from sendto() is correct. So it seems that Python feeds the byte array to a buffer to be sent (by OS?) but stops there.

import socket
CLNT_UDP_IP = '192.168.0.64'
CLNT_UDP_PORT = 5005
svr_sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)

send_data = [0x00, 0x11...]
send_data_arr = bytearray (send_data)
svr_sock.bind (('192.168.0.116',0))  
bytes_send = svr_sock.sendto (send_data_arr, (CLNT_UDP_IP, CLNT_UDP_PORT))
svr_sock.close()

I have taken out the try-except blocks for clarity.

Another thing I noted is that when the socket is closing, it takes a bit of time. If I comment out the sendto statement, it exits immediately. So it seems like the socket close is trying to flush the send buffers, which failed to send the packet.

Any ideas?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Kaush
  • 51
  • 2
  • I think if you want UDP, you should use socket.SOCK_DGRAM and socket.IPPROTO_UDP socket type. Otherwise you have to create the packet header manually. – Ilya Polenov Jul 09 '15 at 05:30
  • Thanks Ilya, I first try with UDP and had the same behavior. Then I thought that 'sendto' may be relying on some additional info from the slave, which it doesn't respond to. (When I send the same to another computer, it works) Thats why I am trying on raw data. The buffer 'send_data[]' contains a full Ethernet packet that I have already verified using Ostinato. – Kaush Jul 13 '15 at 23:19

1 Answers1

0
  1. Ilya is right, you should be opening a UDP socket with

    socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

  2. You're binding to port 0, which is invalid. If this is not an inbound port, you don't need to bind it. This may explain why your sendto call is blocking.

  3. The send_data array should contain only your data, not "the full ethernet packet".

  4. The send_data array must be under the MTU size for your network, otherwise it may be dropped silently. It varies but under 1300 should work, over 1500 almost certainly won't work.

polhemic
  • 166
  • 1
  • 5