Home > front end >  I am trying to generate a random hexadecimal number in python and send it over UDP
I am trying to generate a random hexadecimal number in python and send it over UDP

Time:01-06

Here is my python code:

import socket
data = bytes.fromhex("47 A2 62 19 20 00 00 00 00")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) 
ADDRESS = ("192.168.0.1",9000)
s.connect(ADDRESS)
s.send(data)

I want to put 4 random hexadecimal bytes after "47 A2 62 19 20 00 00 00 00". For example "47 A2 62 19 20 00 00 00 00 20 1E 4A 72". I wonder what to do. Or is there a better way?

CodePudding user response:

random.randbytes can generate random bytes for you. Note that a hexdecimal pair is two bytes, not one byte, so you'll need eight random bytes, not four:

import random
data = bytes.fromhex("47 A2 62 19 20 00 00 00 00")   random.randbytes(8)
  •  Tags:  
  • Related