3
votes

I communicate Python with Matlab via sockets. However, even before going there, I want to test sockets with netcat. So I establish server using nc -lkp 25771, and make Python client to send a message to this server:

import socket
host = 'localhost'
port = 25771
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('Hello there')
s.close()

After running python client.py server prints out 'Hello there'; however, after I try to run client script one more time it raises exception.

Traceback (most recent call last): File "client.py", line 13, in s.connect((host,port)) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 111] Connection refused

Why the same command raises the error second time? What changes after my first command?

1
Are you sure you passed -k option to the nc command?falsetru
Does the problem appear even if you wait few seconds between calls?Michał
I use k option. However, now it's clear why there is a connection error. Once I ran my script and close connection, it shuts nc server down. The question now is how to make nc to listen to second client after the first is done?Sergey Ivanov

1 Answers

0
votes

You are using traditional version of netcat (netcat-traditional) which doesn't support -k option. you can confirm checking the man page of your netcat by typing man nc in your terminal .

Install the netcat-openbsd version using the command sudo apt-get install netcat-openbsd

now switch to netcat-openbsd version using the command

sudo update-alternatives --config nc and choose the netcat-openbsd .

now you can use nc -lk 25771 . this listens on port 25771 for multiple connections .

you can also use the commands discussed here Netcat: using nc -l port_number instead of nc -l -p port_number