user2536262
user2536262

Reputation: 279

Getting started with network programming in Python

I am quite new to Python, and even newer to network programming. I'm starting with this example from docs.python.org:

Server:

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

Client:

# Echo client program
import socket

HOST = 'localhost'        # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

The original code listed some other address as host, I've changed it to localhost. The first time I ran the programs they were stopped by the firewall, but I let it make an exception, and that has not been a problem since.

However, neither of the programs work. The server program gets this error:

Traceback (most recent call last):
  File "C:\Users\Python\echoclient.py", line 7, in <module>
    s.connect((HOST, PORT))
  File "C:\Python27\lib\socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 10061] Det gick inte att göra en anslutning eftersom måldatorn aktivt nekade det

("A connection could not be made because the target computer actively denied it")

The client program gets this error:

Traceback (most recent call last
File "C:\Users\Python\echoclient.py", line 9, in <module> data = s.recv(1024)
error: [Errno 10054] En befintlig anslutning tvingades att stänga av fjärrvärddatorn

("Existing connection was forced to close by remote host")

I am using Python 2.7.6. How do I make this work?

Upvotes: 1

Views: 926

Answers (1)

UnX
UnX

Reputation: 451

Question already asked here : Errno 10061 in python, I don't know what do to

When you have a problem with a network connection on windows, check the Errno number to understand.

In your case, since you are running the app on localhost, maybe you have a firewall rule blocking the server script to bind with port on machine.

To check if app is listening:

On windows, open a cmd prompt (run as Administrator):

netstat -ban | findstr "50007"

On Linux :

netstat -ltnp | grep 50007 

=> If you don't see anything returned, it means nothing is listening on this port.

=> If you see something, check it is your app.

If so, check your firewall rules, antivirus ( best is to disable all sec if you are troubleshooting and it is a test machine)

On windows, go to firewall settings

On Linux, iptables -L -n as root ( or sudo)

Upvotes: 1

Related Questions