Getting started with network programming in Python - 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?

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)

Related

Simple TCP EchoServer in Python

I found this script of TCP server which "echoes" back the data to the client.
#!/usr/bin/env python
import socket
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
if data:
client.send(data)
client.close()
I'm trying to test & understand it before I will be able to do something on my own and modify, but I'm having some problems. When I'm trying to run the .py script I get the following error in my Terminal (using Ubuntu 14.04 LTS)
> Traceback (most recent call last):
File "echo.py", line 14, in <module>
s.bind((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
My Python version is 2.7.6
is there something wrong with the code or I'm doing something wrong?
UPDATE:
it gets worse, any script I run with bind(host, port) gives me the same error.
any help would be appreciated
Perhaps you accidentally ran the EchoServer twice in different windows? You can only bind one receiver to a port/address combination.
Seems like there is some other application running on those ports.
Can you try checking if there are any other app listening on same port using:
netstat -ntlpu | grep 50000
To bind a server it's a little confusing but you have to use a tuple. The correct way is server.bind((host, port))

Getting error while binding a socket

I am scripting a server to use at many things, gaming, data-transfer, chatting etc.
My problem is i am getting this error:
Traceback (most recent call last):
File "server.py", line 11, in <module>
s.bind((host, port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required
I am at the beginning of my server script so far and i scripted many networking scripts before. There shouldnt be any problem. I tried this script both on my local and on my servers and still same resuly and the exact same error. I will really appreciate any kind of help.
Here is my code:
#!/usr/bin/python
# This is server file
import socket
# server & connection settings
host = '127.0.0.1'
port = '5002'
s = socket.socket() # Creating socket object
s.bind((host, port))
s.listen(10)
# server & connection settings
while True:
c,addr = s.accept() # Establish connection with clients.
print 'Got connection from ', addr # Print ip adress of the recently connected client.
c.send('You succesfully established connection with our servers.') # Send socket to the client.
print 'Socket had been sent to the client: ', addr # Print to the server console that we succesfully established connection with the client
c.close() # Close the client connection. Bye, bye! /// Will delete this part when the time come

socket.error: [Errno 111] when trying to connect to a socket

I was trying to write a code where a client connects to server on a default port number, the server then sends another port number to the client. The client now connects to the new port number.
Client:
import socket
import sys
import os
import signal
import time
s = socket.socket()
s.connect(("127.0.0.1", 6667))
line = s.recv(1024)
if line.strip():
port = int(line)
s.close()
soc = socket.socket()
soc.connect(("127.0.0.1", port))
print soc.recv(1024)
soc.close()
else:
s.close()
Server:
import socket
import sys
import os
import signal
import time
port = 7777
s = socket.socket()
s.bind(("127.0.0.1", 6667))
s.listen(0)
sc, address = s.accept()
print address
sc.send(str(port))
sc.close()
s.close()
sock = socket.socket()
sock.bind(("127.0.0.1", port))
soc, addr = sock.accept()
print addr
soc.send("Success")
soc.close()
sock.close()
When I execute this code, I am getting following errors on client and server sides.
Server:
('127.0.0.1', 36282)
Traceback (most recent call last):
File "server.py", line 17, in <module>
soc, addr = sock.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
socket.error: [Errno 22] Invalid argument
Client:
Traceback (most recent call last):
File "client.py", line 13, in <module>
soc.connect(("127.0.0.1", port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Can someone explain me the reason for these errors and provide a solution for these errors.
Before you can listen to a TCP/IP socket (a connection based streaming socket) you need to use bind to assign a socket (created with socket.socket()) . Then you need to do listen to prepare it for incoming connections and then finally you do accept on the prepared socket.
You appear to be missing sock.listen(0) after your call to sock.bind(("127.0.0.1", port)). The Python documentation is short on details but it does say this about TCP/IP:
Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept().
Python bases its socket module on a Berkeley Socket model. You can find some more detailed information on Berkeley Sockets at this link . In particular it says this about bind:
bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts.
Also consider what would happen if your client gets sent a port number (and tries to connect) before the server starts listening for connections (on port 7777 in this case). Although not the cause of your problems, I wanted to point out the scenario for completeness. Something you may consider is not closing the port 6667 socket until after you have called listen on the port 7777 socket. After calling listen you can then close down the first socket. On the client after reading the port you can wait until the first connection (port 6667) is closed down by the server and then connect to port 7777.

getting a socket.gaierror Error 2 when using an actual hostname defined in /etc/hosts, but do not get error with localhost

I have copied simple server/client python programs to test some socket communications.
If host is defined as 'localhost' or '', they work.
If I substitute the actual hostname in /etc/hosts, they fail with the socket.gaierror 2.
socket.gethostname() returns the correct value
as does 'hostname' on the command line.
Here is the server code that fails
#!/usr/bin/env python
"""
A simple echo server
"""
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print( " using host [%s] " % (host) )
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
print( data )
if data:
client.send(data)
client.close()
and here is the client program
#!/usr/bin/env python
"""
A simple echo client
"""
import socket
host = 'localhost'
port = 50000
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.connect((host,port))
s.send('Hello, world')
data = s.recv(size)
s.close()
print( 'Received:', data )
This is the actual output from the server.py while using the gethostname() call.
using host [HP-linux]
Traceback (most recent call last):
File "server.py", line 18, in <module>
s.bind((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -2] Name or service not known
Like I said, if I comment out the 'gethostname() calls, they work.
I have not been able to find any posts about gaierrors that have answers that work to solve this issue.
This running on SuSE Linux 13.1, and python2.7.
Thanks
This issue was resolved by adding an alias to the /etc/hosts file.
No rational answer as to why this would work.
Binding the server on hostname you're actualy binding it on local address, this is because normally there's a line in /etc/hosts like this 127.0.1.1 somehostname, this is to use lo iface instead of eth on the same machine for optimization reasons. If you want to accept connections from all interfaces use '0.0.0.0' instead.
I simply did these steps.
Ran command:
hostname
Say it returned me a value 'yourHostName'
Make an entry in your /etc/hosts file as follows.
127.0.0.1 yourHostName localhost
Reference for this information is : format of /etc/hosts file. Which you can see here.

How to fix Error 61 (Mac) and Error 10061(Windows) using Python 2.7.3

I am currently attempting to create a basic LAN socket server, which works correctly when I use both the client and the server on the same computer. When I attempt to use the client and server on two computers (mac and windows) the connection is consistently refused on the client side. Here is the error that I got on my mac:
Traceback (most recent call last):
File "/Users/*****/Desktop/Client V2.py", line 31, in <module>
s.connect((host, port))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py",
line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 61] Connection refused
On my windows I had the same error, only the number was different. I have turned off windows firewall for both incoming and outgoing connections, and I am confused as to what the actual issue is. Here is the code that I had for my ports:
Client
#Get host and port info to connect
host = 'localhost'
port = input ("What is the PORT number?")
I am not sure if these lines are necessary, perhaps they are the root cause of the problem:
try:
remote_ip = socket.gethostbyname(host)
except socket.gaierror:
#could not resolve
print "Hostname could not be resolved. Exiting"
sys.exit()
And finally, the actual code that connects. (I called the socket s)
s.connect((host, port))
Server
HOST = 'localhost' #Symbolic name meaning all available interfaces
PORT = input ("Enter the PORT number (1 - 10,000)")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket Created"
try:
s.bind((HOST, PORT))
except socket.error, msg:
print "Bind failed. Error Code : " + str(msg[0]) + " Message " + str(msg[1])
sys.exit()
print "Socket Bind Complete"
s.listen(10)
print "Socket now listening"
I am certain that I have done something really silly, but can someone please tell me what my mistake is (or if this is even possible cross-os). I already posted here, but no one responded. I have several other questions there, and it would be great if someone could attempt to answer them.
HOST = 'localhost' #Symbolic name meaning all available interfaces
doesn't mean "all available interfaces" but only the local machine via a special interface only visible to programs running on the same computer.
HOST = '0.0.0.0' #Symbolic name meaning all available interfaces
does mean all available network interfaces. Of course you can also bind to a specific network interface, in that case you just enter its ip address in the field.

Categories