Home > OS >  Trying to send string variable via Python socket
Trying to send string variable via Python socket

Time:09-14

I'm in a CTF competition and I'm stuck on a challenge where I have to retrieve a string from a socket, reverse it and get it back. The string changes too fast to do it manually. I'm able to get the string and reverse it but am failing at sending it back. I'm pretty sure I'm either trying to do something that's not possible or am just too inexperienced at Python/sockets/etc. to kung fu my way through.

Here's my code:

import socket

aliensocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

aliensocket.connect(('localhost', 10000))
  
aliensocket.send('GET_KEY'.encode())
key = aliensocket.recv(1024)

truncKey = str(key)[2:16]
revKey = truncKey[::-1]

print(truncKey)
print(revKey)

aliensocket.send(bytes(revKey.encode('UTF-8')))
print(aliensocket.recv(1024))

aliensocket.close()

And here is the output:

F9SIJINIK4DF7M
M7FD4KINIJIS9F
b'Server expects key to unlock or GET_KEY to retrieve the reversed key'

CodePudding user response:

key is received as a byte string. The b'' wrapped around it when printed just indicates it is a byte string. It is not part of the string. .encode() turns a Unicode string into a byte string, but you can just mark a string as a byte string by prefixing with b.

Just do:

aliensocket.send(b'GET_KEY')
key = aliensocket.recv(1024)
revKey = truncKey[::-1]
print(truncKey)  # or do truncKey.decode() if you don't want to see b''
print(revKey)
aliensocket.send(revKey)

CodePudding user response:

data  = ''
while True:
   chunk = aliensocket.recv(1)
   data  =chunk
   if not chunk:
        rev = data[::-1]
        aliensocket.sendall(rev)
        break
  • Related