0% found this document useful (0 votes)
16 views9 pages

TCP/IP Client and Server in Python

Uploaded by

Corrado Tuccitto
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views9 pages

TCP/IP Client and Server in Python

Uploaded by

Corrado Tuccitto
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TCP/IP Client and Server - Python Module of the... [Link]

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 = [Link](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 >>[Link], 'starting up on Some of the features described here may
[Link](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


[Link](1)

while True:
# Wait for a connection
print >>[Link], '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 >>[Link], '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... [Link]

while True:
data = [Link]
print >>[Link], 'received "
if data:
print >>[Link]
SMS Text
[Link] Gateway
else:
print >>[Link]
break Connect to 960+
MNOs with 1 API.
finally:
# Clean up the connection
98.9% Delivered
[Link]() <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 = [Link](socket.AF_INET

# Connect the socket to the port where the server


server_address = ('localhost', 10000
print >>[Link], 'connecting to
[Link](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 >>[Link], 'sending "
[Link](message)

# Look for the response


amount_received = 0
amount_expected = len(message

while amount_received < amount_expected


data = [Link](16)
amount_received += len(data
print >>[Link], 'received "

finally:
print >>[Link], 'closing socket'
[Link]()

2 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... [Link]

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 ('[Link]', 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 ('[Link]', 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 [Link](
)

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... [Link]

print >>[Link], 'Family :',


print >>[Link], 'Type :',
print >>[Link], 'Protocol:',
print >>[Link]

try:

# Send data
message = 'This is the message. It will be re
print >>[Link], 'sending "
[Link](message)

amount_received = 0
amount_expected = len(message

while amount_received < amount_expected


data = [Link](16)
amount_received += len(data
print >>[Link], 'received "

finally:
print >>[Link], 'closing socket'
[Link]()

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... [Link]

# Create a TCP/IP socket


sock = [Link](socket.AF_INET

# Bind the socket to the address given on the comm


server_name = [Link][1]
server_address = (server_name, 10000
print >>[Link], 'starting up on
[Link](server_address)
[Link](1)

while True:
print >>[Link], 'waiting for a connection'
connection, client_address =
try:
print >>[Link], 'client connected:'
while True:
data = [Link]
print >>[Link], 'received "
if data:
[Link]
else:
break
finally:
[Link]()

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 = [Link](socket.AF_INET

# Connect the socket to the port on the server giv


server_address = ([Link][1], 10000
print >>[Link], 'connecting to
[Link](server_address)

try:

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


print >>[Link], 'sending "
[Link](message)

amount_received = 0
amount_expected = len(message
while amount_received < amount_expected
data = [Link](16)
amount_received += len(data
print >>[Link], 'received "

finally:
[Link]()

After starting the server with the argument


[Link] , the netstat command
shows it listening on the address for the named host.

$ host [Link]

[Link] has address [Link]

$ netstat -an

5 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... [Link]

Active Internet connections (including servers)


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

Running the the client on another host, passing


[Link] as the host where the
server is running, produces:

$ hostname

homer

$ python socket_echo_client_explicit.py farnsworth

connecting to [Link] 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 [Link] port 10000


waiting for a connection
client connected: ('[Link]', 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 = [Link](socket.AF_INET

# Bind the socket to the address given on the comm


server_address = ('', 10000)
[Link](server_address)
print >>[Link], 'starting up on
[Link](1)

while True:
print >>[Link], 'waiting for a connection'

6 of 9 10/06/2014 12:15 AM
TCP/IP Client and Server - Python Module of the... [Link]

connection, client_address =
try:
print >>[Link], 'client connected:'
while True:
data = [Link]
print >>[Link], 'received "
if data:
[Link]
else:
break
finally:
[Link]()

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... [Link]

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 [Link] ,
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... [Link]

[Link] - Hotel
[Link]/Alberghi
Il sito uf�ciale di [Link]! 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