Python - Network Programming

Python - Network Programming
Techiio-author
Written by Sagar RabidasNovember 25, 2021
11 min read
Python
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Today we will cover Python - Network Programming.

Python

Python offers two levels of getting entry to community services. At a low degree, you can get entry to the basic socket support in the underlying operating device, which allows you to enforce clients and servers for each connection-orientated and connectionless protocol.

Python additionally has libraries that provide higher-level get entry to particular software-degree network protocols, consisting of FTP, HTTP, and so forth.

This chapter offers you expertise on the maximum famous concept in networking - socket programming.

Sockets:-

Sockets are the endpoints of a bidirectional communications channel. Sockets may also communicate within a technique, between approaches at the equal device, or between tactics on different continents.

Sockets may be applied over some of one-of-a-kind channel kinds: Unix domain sockets, TCP, UDP, and so on. The socket library offers unique lessons for coping with the common transports in addition to a usual interface for coping with the rest.

Sockets have their own vocabulary −

  • Domain

The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

  • Type

The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.

  • Protocol

Typically zero, this may be used to identify a variant of a protocol within a domain and type.

  • Hostname

The identifier of a network interface −

  1. A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation
  2. A string "<broadcast>", which specifies an INADDR_BROADCAST address.
  3. A zero-length string, which specifies INADDR_ANY, or
  4. An Integer, interpreted as a binary address in host byte order.

  • Port

Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.

The socket Module

To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax −

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

Here is the description of the parameters −

  • socket_family − This is either AF_UNIX or AF_INET, as explained earlier.

  • socket_type − This is either SOCK_STREAM or SOCK_DGRAM.

  • protocol − This is usually left out, defaulting to 0.

Once you have socket object, then you can use required functions to create your client or server program. Following is the list of functions required −

Server Socket Methods

  • s.bind()

This method binds address (hostname, port number pair) to socket.

  • s.listen()

This method sets up and start TCP listener.

  • s.accept()

This passively accept TCP client connection, waiting until connection arrives (blocking).

Client Socket Methods

  • s.connect()

This method actively initiates TCP server connection.

General Sockets

  • s.recv()

This method receives TCP message

  • s.send()

This method transmits TCP message

  • s.recvfrom()

This method receives UDP message

  • s.sendto()

This method transmits UDP message

  • s.close()

This method closes socket

  • socket.gethostname()

Returns the hostname.

A Simple Server

To put in writing internet servers, we use the socket characteristic available in socket module to create a socket item. A socket item is then used to call different functions to setup a socket server.

Now name bind(hostname, port) characteristic to specify a port on your carrier at the given host.

Next, call the receive technique of the again object. This technique waits till a consumer connects to the port you particular, and then returns a connection item that represents the relationship to that consumer.

#!/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

Allow us to write a completely easy customer program which opens a connection to a given port 12345 and given host. This is very simple to create a socket customer the usage of python's socket module function.

The socket.Connect(hosname, port ) opens a tcp connection to hostname on the port. Once you have a socket open, you may examine from it like all io item. When finished, do not forget to shut it, as you would close a document.

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 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 background and then run above client.py to see the result.

# Following would start a server in background.
$ python server.py & 
# Once server is started run client as follows:
$ python client.py

This would produce following result −

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

Python Internet modules

A list of some important modules in Python Network/Internet programming.

blogpost

phthon
networking
http
0 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 0 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance