Python Network Programming – GeeksforGeeks

Python provides two levels of access to network programming. These are – 

  • Low-Level Access: At the low level, you can access the basic socket support of the operating system. You can implement client and server for both connection-oriented and connectionless protocols.
  • High-Level Access: At the high level allows to implement protocols like HTTP, FTP, etc.

In this article, we will discuss Network Socket Programming. But before getting started let’s understand what are sockets.

What are Sockets?

Consider a bidirectional communication channel, the sockets are the endpoints of this communication channel. These sockets (endpoints) can communicate within a process, between processes on the same machine, or between the processes on the different machines. Sockets use different protocols for determining the connection type for port-to-port communication between clients and servers.

Sockets Vocabulary

Sockets have their own set of vocabulary, let’s have a look at them – 

TermDescriptionDomainThe set of protocols used for transport mechanisms like AF_INET, PF_INET, etc.TypeType of communication between socketsProtocolIdentifies the type of protocol used within domain and type. Typically it is zeroPortThe server listens for clients calling on one or more ports. it can be a string containing a port number, a name of the service, or a Fixnum portHostname

Identifies a network interface. It can be a 

  • a string containing hostname, IPv6 address, or a double-quad address.
  • an integer
  • a zero-length string
  • a string “<broadcast>”

Socket Programming

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. They are the real backbones behind web browsing. In simpler terms, there is a server and a client. We can use the socket module for socket programming. For this, we have to include the socket module – 

import socket

to create a socket we have to use the socket.socket() method. 

Syntax:

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

Where, 

  • socket_family: Either AF_UNIX or AF_INET
  • socket_type: Either SOCK_STREAM or SOCK_DGRAM.
  • protocol: Usually left out, defaulting to 0.

Example:

Python3




import socket

 

 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print(s)



Output:

<socket.socket fd=74, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(‘0.0.0.0’, 0)>

The socket module provides various methods for both client and server-side programming. Let’s see each method in detail.

Socket Server Methods

These methods are used on the server-side. Let’s see each method in detail – 

Function NameDescriptions.bind()Binds address to the socket. The address contains the pair of hostname and the port number.s.listen()Starts the TCP listeners.accept()Passively accepts the TCP client connection and blocks until the connection arrives

Socket Client Methods

This method is used on the client side. Let’s see this method in detail – 

Function NameDescriptions.connect()Actively starts the TCP server connection

Socket General Methods

These are the general methods of the socket module. Let’s see each method in detail.

Function NameDescriptions.send()Sends the TCP messages.sendto()Sends the UDP messages.recv()Receives the TCP messages.recvfrom()Receives the UDP messages.close()Close the socketsocket.ghostname()Returns the host name

Simple Server Client Program

Server

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listening mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client. 

Example: Network Programming Server-Side

Python3




import socket

 

s = socket.socket()

print ("Socket successfully created")

 

port = 40674

 

s.bind(('', port))

print ("socket binded to %s" %(port))

 

s.listen(5)   

print ("socket is listening")

 

while True:

 

    

    c, addr = s.accept()

    print ('Got connection from', addr )

 

    

    c.send(b'Thank you for connecting')

 

    

    c.close()



Explanation:

  • We made a socket object and reserved a port on our pc.
  • After that, we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
  • After that, we put the server into listening mode. 5 here means that 5 connections are kept waiting if the server is busy and if a 6th socket tries to connect then the connection is refused.
  • At last, we make a while loop and start to accept all incoming connections and close those connections after a thank you message to all connected sockets.

Client

Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal:

# start the server
python server.py

# keep the above terminal open
# now open another terminal and type:

telnet localhost 12345

Output :

network programing server side

In the telnet terminal you will get this:

network programming telnet server

This output shows that our server is working. Now for the client-side: 

Example: Network Programming Client Side

Python3




import socket

 

s = socket.socket()

 

port = 40674

 

s.connect(('127.0.0.1', port))

 

print(s.recv(1024))

 

s.close()



Output:

python network programming server clientpython network programming client side

Explanation:

  • We connect to localhost on port 40674 (the port on which our server runs) and lastly, we receive data from the server and close the connection.
  • Now save this file as client.py and run it from the terminal after starting the server script.

Note: For more information on Socket Programming refer to our Socket Programming in Python Tutorial

My Personal Notes

arrow_drop_up