Sending hexadecimal values ​​via UDP or TCP socket via parameter passing to script

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

I have a python script udp_send.py and I want to send a hexadecimal value to represent a server-side register value.

I ran my script through linux terminal -> python udp_send.py "\ x41". I read the variable using argv [1] in my python script. I checked, and this is 3. It ignores \ and accepts x, 4 and 1 as 1 byte each, while I want \ x41 to represent only 1 byte.

Then I tried to combine the data = "\ x" + "41", but that did not work.

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

I have so far achieved the following results. Send the 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 wirehark on the server side and saw the 41 hex value.

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

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

+3
source share
2

, 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)
+3

, . . "A", .

, '\ x41' 'A' python. , 0x41. ( 0100 0001). ( python), , . - , python. , , ( \x escape- ), x unescaped, 4 1. , python x 4 1. , , , . python , \, x, 4 1. '\\x4a', , \x4a.

0x41, A.

+1

All Articles