Python Network Programming Socket Programming

Python Network Programming: Socket Programming

Python provides two levels of access to network services. At the low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.

Python There are also libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.

A socket is an endpoint of a bidirectional communication channel. Sockets can be used to communicate within a process, between processes on the same machine, or between processes on different continents. We use the Python socket module to create and use sockets.

Sockets have their own vocabulary.

Sr. No. Term and Description
1 **Domain** The protocol family used as the transport mechanism. These values are constants, such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
2 **type** The type of communication between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
3 protocol Typically zero, can be used to identify a protocol variant within a domain and type.
4 hostname An identifier for a network interface:
A string that can be a host name, a dotted quad address, or an IPv6 address represented by a colon (and possibly a dot).
A string <broadcast> that specifies an INADDR_BROADCAST address.
A zero-length string that specifies INADDR_ANY, or
An integer interpreted as a binary address in host byte order.
5 port Each server listens for clients calling it on one or more ports. A port can be a Fixnum port number, a string containing a port number, or a service name.

The socket module

To create a socket, you must use the socket.socket() function in the socket module. Its general syntax is: –

s = socket.socket (socket_family, socket_type, protocol=0)

Following is a description of the parameters: −

  • socket_family – This is either AF_UNIX or AF_INET, as described previously.
  • socket_type – This is either SOCK_STREAM or SOCK_DGRAM.

  • protocol – This is usually omitted and defaults to 0.

Once you have a socket object, you can use the necessary functions to create your client or server program.

Server Socket Methods

Number Method and Description
1 s.bind() This method binds an address (hostname, port number pair) to a socket.
2 s.listen() This method sets up and starts a TCP listener.
3 s.accept() This method passively accepts TCP client connections, waiting for incoming connections (blocking).

Client Socket Methods

Sequence Number Method and Description
1 s.connect() This method actively initiates a TCP server connection.

General socket methods

Serial number: Sr.No. Method and description
1 s.recv() This method receives TCP messages.
2 s.send() This method sends TCP messages.
3 s.recvfrom() This method receives UDP messages.
4 s.sendto() This method sends a UDP message.
5 s.close() This method closes the socket.
6 socket.gethostname() Returns the host name.

A Simple Server

To write an Internet server, we use the socket function in the socket module to create a socket object. The socket object is then used to call other functions to set up a socket server.

Now call the bind(hostname, port) function to assign a hostname to your service on a given host. Port.

Next, call the Accept method of the returned object. This method waits for a client to connect to the port you specified and then returns a Connection object representing the connection with the client.

#!/usr/bin/python # This is server.py file

import socket # Import socket module

s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port

s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the Connection

A Simple Client

Let’s write a very simple client program that opens a connection to a given port 12345 and a given host. Creating a socket client is very simple using Python’s socket module functions.

socket.connect(hosname, port) opens a TCP connection to hostname on port . Once you have a socket open, you can read from it like any IO object. When you are done, remember to close it, just like you would a file.

The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits.

#!/usr/bin/python # This is client.py file

import socket # Import socket module

s = socket.socket() # Create a socket object
host = socket.gethostname() # Get the local machine name
port = 12345 # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done

Now run this server.py in the background, then run the client.py above and see the results.

# Following would start a server in background.
<span class="katex math inline">python server.py&

# Once the server is started, run the client as follows:</span> python client.py

This will produce the following results –

Got connection from ('127.0.0.1', 48437)
Thank you for Connecting

Sockets with Public URLs

In the following example, we use some methods of the socket module to find the server’s address information and hostname details.

<br>import socket
from pprint import pprint

# get server address
addrinfo = socket.getaddrinfo('tutorialspoint.com', 'www')

pprint(addrinfo)

# get server hostname
print socket.gethostname()

When we run the above program, we get the following output −

[(2, 1, 0, '', ('94.130.81.180', 80))]
DESKTOP-JXYKQCPLP

Leave a Reply

Your email address will not be published. Required fields are marked *