Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python socket strange behavior

I can't understand why this code works fine,

echo as3333 | nc stat.ripe.net 43

but the equivalent code in Python returns nothing

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('stat.ripe.net', 43))
sock.send('as3333'.encode('utf-8'))
tmp = sock.recv(1024)
print(tmp.decode('utf-8')) #no bytes there
sock.close()

Thanks!

like image 341
foo Avatar asked Feb 22 '26 13:02

foo


1 Answers

It is not exactly the same. You forgot the newline and sendall. Fixed code:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('stat.ripe.net', 43))
sock.sendall('as3333\r\n'.encode('utf-8'))

response = b''
while True:
    tmp = sock.recv(65536)
    if not tmp:
        break
    response += tmp

print(response.decode('utf-8'))
sock.close()
like image 175


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!