Search code examples
pythonsocketsencodinghextcpclient

Send Hex data from Client to Server - Python


I have this code, I need to send the following message to the server using TCP:

import socket
import sys

def invia_comandi(s):
    while True:
        comando = input("-> ")
        if comando == "ESC":
            s.close()
            sys.exit()
        else:
            s.send("DATA 457f598514e2adafdb\
          d3234675343aee4c216987a2a1e69c4681d43c6c43978ca59d322105bf00543089\
            75b04e3971bb40407e921f294af6bb91eb0cda8571886bca38301e06fc4fd9c5\r\n".encode())
            #s.send(comando.encode())
            data = s.recv(4096)
            print(str(data, "utf-8"))

def conn_sub_server(indirizzo_server):
    try:
        s = socket.socket()
        s.connect(indirizzo_server)
    except socket.error as errore:
        sys.exit()
    invia_comandi(s)

if __name__ == '__main__':
    conn_sub_server((".....", ....))

I need to send the message DATA 60b4151f093363cc4fc2b4575e531bac3e715ae59b33b5136f598514e2adafdb d3234675343aee4c216987a2a1e69c4696610b1eb8b9ce3c54325b65e8de0d98be8074927c0f037288e9eba3530f4a81d43c6c43978ca59d322105bf0054308975b04e3971bb40407e921f294af6bb91eb0cda8571886bca38301e06fc4fd9c5\r\n to the server. When I try executing this I get ERROR Invalid hexadecimal character ' '. How can I do? Thanks


Solution

  • If you put text in many lines then you have to start next line in first column because Python doesn't know that you want to skip spaces and it add spaces to DATA.

    def invia_comandi(s):
        while True:
            comando = input("-> ")
            if comando == "ESC":
                s.close()
                sys.exit()
            else:
                s.send("DATA 60b4151f093363cc4fc2b4575e531bac3e715ae59b33b5136f598514e2adafdb\
    d3234675343aee4c216987a2a1e69c4696610b1eb8b9ce3c54325b65e8de0d98\
    be8074927c0f037288e9eba3530f4a81d43c6c43978ca59d322105bf00543089\
    75b04e3971bb40407e921f294af6bb91eb0cda8571886bca38301e06fc4fd9c5\r\n".encode())
    

    Or you should use quote in every line (but without \)

    def invia_comandi(s):
        while True:
            comando = input("-> ")
            if comando == "ESC":
                s.close()
                sys.exit()
            else:
                s.send("DATA 60b4151f093363cc4fc2b4575e531bac3e715ae59b33b5136f598514e2adafdb"
                "d3234675343aee4c216987a2a1e69c4696610b1eb8b9ce3c54325b65e8de0d98"
                "be8074927c0f037288e9eba3530f4a81d43c6c43978ca59d322105bf00543089"
                "75b04e3971bb40407e921f294af6bb91eb0cda8571886bca38301e06fc4fd9c5\r\n".encode())
    

    So you had spaces in your DATA and it had problem to convert space from hex to number - and this gives ERROR Invalid hexadecimal character ' '