Python – Sending Hex Values through UDP or TCP socket via parameter passing to script

hexparameter-passingpythonsockets

I know in order to send data through a UDP socket using python has to be in the following format "\x41" = A .

I have a python script udp_send.py and I want to send in a hex value to represent a register value on the server side.

I run my script through linux terminal >>python udp_send.py "\x41" . I read the variable using argv[1] in my python script. I did a len check and it is 3 . It ignore \ and take x, 4 and 1 as 1 byte each whereas I want \x41 to represent 1 byte only.

I was then trying to concatenate data="\x"+"41" but it did not work.

"\x" is interpreted as escape by python. I am trying to find a way to pass a hex value into my script and send it via UDP socket?

I have achieved the following so far. Send a hex value defined in python script via UDP socket .

from socket import *
from sys import *

## Set the socket parameters
host = <ip-define-here>
port = <port-define-here>
buf = 1024
addr = (host,port)

## Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

## Send messages
data ='\x41'
#data=argv[1] #commented out
if not data:
    print "No data"
else:
    if(UDPSock.sendto(data,addr)):
        print "Sending message ",data

## Close socket
UDPSock.close()

I used wireshark on server side and saw the hex value 41 appear.

Just to be clear "41"(made of 2 bytes) is not the same as "\x41"(one byte only) in python.

My simple question is, how can I take a character "41" and join it with "\x" to form "\x41" so I can assign it to data variable in my python script so I can send it as hex value 41.

Best Solution

In your code, you can convert your arg to proper format, then you can call it with python udp_send.py 0x41

arg = sys.argv[1]

# intarg = 65 == 0x41
intarg = int(arg, 16)

# now convert to byte string '\x41'
hexstring = struct.pack('B', intarg)
Related Question