Python Networking

« Previous Tutorial Next Tutorial »

Python allows you to two levels of access to the network services:

What is Socket ?

Socket is the endpoint of a bi-directional communications channel. Sockets can communicate within a process, between the processes on the same machine, or between the processes on the different continents.

A Simple Server

To write the internet server, we will use the function socket() available in the socket module to create the socket object. A socket object is then used to call the other functions to setup the socket server. Now call the function named bind(hostname, port) to specify a port for your service on the given host. Next, call the method named accept() of the returned object. This method waits until a client connects to the port you have specified, and then returns a connection object that represents the connection to that client. Here is an example demonstrating all this. This is file:

# Python Networking - Example Program

import socket               # this import the socket module

s = socket.socket()         # this creates a socket object
host = socket.gethostname() # this will get the local machine name
port = 12345                # this reserves a port for your service.
s.bind((host, port))        # this bind to the port

s.listen(5)                 # this wait for the client connection.
while True:
   c, addr = s.accept()     # this establish connection with the client.
   print("Got connection from", addr)
   c.send("Thank you for connecting")
   c.close()                # this will lose the connection

A Simple Client

Here is a simple client program, which opens a connection to a given port 12345 and given host. This is file.

# Python Networking - Example Program

import socket 

s = socket.socket()
host = socket.gethostname()
port = 12345 

s.connect((host, port))


Now run the file in the background and then run the to see the result:

$ python &

$ python

It will produce following result:

Got connection from ('', 48437)
Thank you for connecting

« Previous Tutorial Next Tutorial »


Quick Links
Signup - Login - Give Online Test