Netcat implementation in Python

Does it work if you just use nc?

I think you should try something a little simpler:

import socket

def netcat(hostname, port, content):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.sendall(content)
    s.shutdown(socket.SHUT_WR)
    while 1:
        data = s.recv(1024)
        if len(data) == 0:
            break
        print("Received:", repr(data))
    print("Connection closed.")
    s.close()

I added the shutdown call because maybe your device is waiting for you to say you’re done sending data. (That would be a little weird, but it’s possible.)

Leave a Comment