Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equivalent of netcat

I have a TCP server for which I need to write a client in Python.

The server is an arduino using the arduino_uip library; the server code is (almost) the same as the TCP server example of that library. It works fine using nc as a client.

But when I use python sockets (as in this answer) to communicate with the server, the server hangs on socket shutdown or close.

That may be an issue with the server; however since nc is working fine as a client, my question is :

What does this answer do differently from nc that may explain server hanging on connection shutdown/close)?

Summing up what works & what not :

  • python client & nc -l as server: works
  • nc as client & arduino server : works
  • python client & arduino server: hangs server

Here is the client code :

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 data == "":
            break
        print "Received:", repr(data)
    print "Connection closed."
    s.close()

Edit :

It appears (Vorsprung's answer made me think about it!)that it is in fact a timing problem. If I add sleep(0.5) before shutdown in the above code all works nicely (as in netcat where there is a manual delay before I hit Ctrl+C). I suppose I'll have to check that arduino library now...

like image 756
Nicolas D Avatar asked Nov 02 '22 11:11

Nicolas D


1 Answers

Had a look at the netcat source ( svn checkout svn://svn.code.sf.net/p/netcat/code/trunk netcat-code ) and it only calls shutdown() just before it closes, not just after setting up the socket

That's the difference as far as I can see

like image 75
Vorsprung Avatar answered Nov 09 '22 16:11

Vorsprung