0% found this document useful (0 votes)
12 views

Net Python

Uploaded by

Corrado Tuccitto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Net Python

Uploaded by

Corrado Tuccitto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.

html

PyMOTW
Home TCP/IP Client and Server Page Contents

Blog Sockets can be configured to act as a server and listen TCP/IP Client and Server
for incoming messages, or connect to other applications Echo Server
The Book
as a client. After both ends of a TCP/IP socket are Echo Client
About connected, communication is bi-directional. Client and Server Together
Easy Client Connections
Site Index Echo Server Choosing an Address for Listening

If you find this This sample program, based on the one in the standard Navigation
information useful, library documentation, receives incoming messages and
consider picking up a Table of Contents
echos them back to the sender. It starts by creating a
copy of my book, The Previous: Addressing, Protocol Families
TCP/IP socket.
Python Standard and Socket Types

Library By Example. import socket Next: User Datagram Client and Server
import sys

# Create a TCP/IP socket This Page


sock = socket.socket(socket.AF_INET
Show Source
Then bind() is used to associate the socket with the
server address. In this case, the address is
Examples
localhost , referring to the current server, and the port
number is 10000. The output from all the example programs
from PyMOTW has been generated with
# Bind the socket to the port Python 2.7.4, unless otherwise noted.
server_address = ('localhost', 10000
print >>sys.stderr, 'starting up on Some of the features described here may
sock.bind(server_address) not be available in earlier versions of
Python.
Calling listen() puts the socket into server mode,
and accept() waits for an incoming connection.

# Listen for incoming connections


sock.listen(1)

while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = The Python Standard
Library by Examp...
accept() returns an open connection between the Doug Hellmann
Best Price $24.79
server and client, along with the address of the client. or Buy New $33.87
The connection is actually a different socket on another
port (assigned by the kernel). Data is read from the
connection with recv() and transmitted with Privacy Information

sendall() .

try:
print >>sys.stderr, 'connection from'

# Receive the data in small chunks and ret

1 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

while True:
data = connection.recv
print >>sys.stderr, 'received "
if data:
print >>sys.stderr
SMS Text
connection.sendall Gateway
else:
print >>sys.stderr
break Connect to 960+
MNOs with 1 API.
finally:
# Clean up the connection
98.9% Delivered
connection.close() <1s. Free Trial

When communication with a client is finished, the


connection needs to be cleaned up using close() .
This example uses a try:finally block to ensure
that close() is always called, even in the event of an
error.

Echo Client
The client program sets up its socket differently from
the way a server does. Instead of binding to a port and
listening, it uses connect() to attach the socket
directly to the remote address.

import socket
import sys

# Create a TCP/IP socket


sock = socket.socket(socket.AF_INET

# Connect the socket to the port where the server


server_address = ('localhost', 10000
print >>sys.stderr, 'connecting to
sock.connect(server_address)

After the connection is established, data can be sent


through the socket with sendall() and received
with recv() , just as in the server.

try:

# Send data
message = 'This is the message. It will be re
print >>sys.stderr, 'sending "
sock.sendall(message)

# Look for the response


amount_received = 0
amount_expected = len(message

while amount_received < amount_expected


data = sock.recv(16)
amount_received += len(data
print >>sys.stderr, 'received "

finally:
print >>sys.stderr, 'closing socket'
sock.close()

2 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

When the entire message is sent and a copy received,


the socket is closed to free up the port.

Client and Server Together


The client and server should be run in separate terminal
windows, so they can communicate with each other.
The server output is:

$ python ./socket_echo_server.py

starting up on localhost port 10000


waiting for a connection
connection from ('127.0.0.1', 52186)
received "This is the mess"
sending data back to the client
received "age. It will be"
sending data back to the client
received " repeated."
sending data back to the client
received ""
no more data from ('127.0.0.1', 52186)
waiting for a connection

The client output is:

$ python socket_echo_client.py

connecting to localhost port 10000


sending "This is the message. It will be repeated
received "This is the mess"
received "age. It will be"
received " repeated."
closing socket

Easy Client Connections


TCP/IP clients can save a few steps by using the
convenience function create_connection() to
connect to a server. The function takes one argument, a
two-value tuple containing the address of the server,
and derives the best address to use for the connection.

import socket
import sys

def get_constants(prefix):
"""Create a dictionary mapping socket module c
return dict( (getattr(socket,
for n in dir(socket
if n.startswith(
)

families = get_constants('AF_')
types = get_constants('SOCK_')
protocols = get_constants('IPPROTO_'

# Create a TCP/IP socket


sock = socket.create_connection((

3 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

print >>sys.stderr, 'Family :',


print >>sys.stderr, 'Type :',
print >>sys.stderr, 'Protocol:',
print >>sys.stderr

try:

# Send data
message = 'This is the message. It will be re
print >>sys.stderr, 'sending "
sock.sendall(message)

amount_received = 0
amount_expected = len(message

while amount_received < amount_expected


data = sock.recv(16)
amount_received += len(data
print >>sys.stderr, 'received "

finally:
print >>sys.stderr, 'closing socket'
sock.close()

create_connection() uses getaddrinfo() to


find candidate connection parameters, and returns a
socket opened with the first configuration that creates
a successful connection. The family , type , and
proto attributes can be examined to determine the
type of socket being returned.

$ python socket_echo_client_easy.py

Family : AF_INET
Type : SOCK_STREAM
Protocol: IPPROTO_TCP

sending "This is the message. It will be repeated


received "This is the mess"
received "age. It will be"
received " repeated."
closing socket

Choosing an Address for


Listening
It is important to bind a server to the correct address, so
that clients can communicate with it. The previous
examples all used 'localhost' as the IP address,
which limits connections to clients running on the same
server. Use a public address of the server, such as the
value returned by gethostname() , to allow other
hosts to connect. This example modifies the echo
server to listen on an address specified via a command
line argument.

import socket
import sys

4 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

# Create a TCP/IP socket


sock = socket.socket(socket.AF_INET

# Bind the socket to the address given on the comm


server_name = sys.argv[1]
server_address = (server_name, 10000
print >>sys.stderr, 'starting up on
sock.bind(server_address)
sock.listen(1)

while True:
print >>sys.stderr, 'waiting for a connection'
connection, client_address =
try:
print >>sys.stderr, 'client connected:'
while True:
data = connection.recv
print >>sys.stderr, 'received "
if data:
connection.sendall
else:
break
finally:
connection.close()

A similar modification to the client program is needed


before the server can be tested.

import socket
import sys

# Create a TCP/IP socket


sock = socket.socket(socket.AF_INET

# Connect the socket to the port on the server giv


server_address = (sys.argv[1], 10000
print >>sys.stderr, 'connecting to
sock.connect(server_address)

try:

message = 'This is the message. It will be re


print >>sys.stderr, 'sending "
sock.sendall(message)

amount_received = 0
amount_expected = len(message
while amount_received < amount_expected
data = sock.recv(16)
amount_received += len(data
print >>sys.stderr, 'received "

finally:
sock.close()

After starting the server with the argument


farnsworth.hellfly.net , the netstat command
shows it listening on the address for the named host.

$ host farnsworth.hellfly.net

farnsworth.hellfly.net has address 192.168.1.17

$ netstat -an

5 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

Active Internet connections (including servers)


Proto Recv-Q Send-Q Local Address Foreig
...
tcp4 0 0 192.168.1.17.10000 *.*
...

Running the the client on another host, passing


farnsworth.hellfly.net as the host where the
server is running, produces:

$ hostname

homer

$ python socket_echo_client_explicit.py farnsworth

connecting to farnsworth.hellfly.net port 10000


sending "This is the message. It will be repeated
received "This is the mess"
received "age. It will be"
received " repeated."

And the server output is:

$ python ./socket_echo_server_explicit.py farnswor

starting up on farnsworth.hellfly.net port 10000


waiting for a connection
client connected: ('192.168.1.8', 57471)
received "This is the mess"
received "age. It will be"
received " repeated."
received ""
waiting for a connection

Many servers have more than one network interface,


and therefore more than one IP address. Rather than
running separate copies of a service bound to each IP
address, use the special address INADDR_ANY to listen
on all addresses at the same time. Although socket
defines a constant for INADDR_ANY , it is an integer
value and must be converted to a dotted-notation string
address before it can be passed to bind() . As a
shortcut, use the empty string '' instead of doing the
conversion.

import socket
import sys

# Create a TCP/IP socket


sock = socket.socket(socket.AF_INET

# Bind the socket to the address given on the comm


server_address = ('', 10000)
sock.bind(server_address)
print >>sys.stderr, 'starting up on
sock.listen(1)

while True:
print >>sys.stderr, 'waiting for a connection'

6 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

connection, client_address =
try:
print >>sys.stderr, 'client connected:'
while True:
data = connection.recv
print >>sys.stderr, 'received "
if data:
connection.sendall
else:
break
finally:
connection.close()

To see the actual address being used by a socket, call


its getsockname() method. After starting the service,
running netstat again shows it listening for incoming
connections on any address.

$ netstat -an

Active Internet connections (including servers)


Proto Recv-Q Send-Q Local Address Foreig
...
tcp4 0 0 *.10000 *.*
...

7 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

Comments Community

 Login

Sort by Best Favorite ★


Share ⤤

Join the discussion…

Drew Green
• 2 years ago
This is great - thanks
for the guide!
1 • Reply •
Share ›

Хайрый
Сархад Төлек
• 7 months ago
Very helpful. Many
thanks
• Reply •
Share ›

BenFriman
• a year ago
Thanks. Using netstat
-an solved my
problem of getting the
listening to work via a
router with port
forwarding. I looked
at how the listening
was set up for SSH,
where the "host" IP
address was 0.0.0.0 ,
copied that for my
listening and it now
works!
• Reply •
Share ›

Masood
Mansoori
• a year ago
Very helpful, Thank

8 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... http://pymotw.com/2/socket/tcp.html

Booking.com - Hotel
www.booking.com/Alberghi
Il sito uf�ciale di Booking.com! Offerte ed Hotel di ogni
categoria.
© Copyright Doug Hellmann. | | Last updated on Aug 31, 2014. | Created using Sphinx. | Design based on "Leaves" by SmallPark |

9 of 9 10/06/2014 12:15 AM

You might also like