Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
How networks are categorised?
3.
Python for Network Programming
4.
Socket Programming in Python
5.
Frequently asked questions
5.1.
What is socket programming?
5.2.
What are the two types of sockets?
5.3.
How many connections can be in a socket?
6.
Conclusion
Last Updated: Jul 3, 2024
Medium

Network Fundamentals & Socket Programming

Author Urwashi Priya
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

There are several reasons for using Python for Network Programming. The simplicity of python makes it the most powerful language.

Network Fundamentals: Computer Networking aims to study and analyse the communication process among various computing devices or computer systems that are linked, or networked together to exchange information and share resources. In order to perform networking, we must have a network. A network is simply a group of two or more Personal Computers linked together. Many types of networks exist, but the most common types of networks are Local-Area Networks (LANs), and Wide-Area Networks (WANs).

In a LAN, computers are connected together within a “local” area (for example, an office or home). In a WAN, computers are further apart and are connected via telephone/communication lines, radio waves or other means of connections.

Read More, Python for Data Science

How networks are categorised?

Networks are usually classified using three properties: Topology, Protocols and Architecture. 

Topology: It specifies the geometric arrangement of the network. Common topologies are a bus, ring and star.

Protocol: It specifies a common set of rules and signals the computers on the network use to communicate. Most networks use Ethernet, but some networks may use IBM’s Token Ring protocol. Mostly Ethernet is used for both home and office networking.

Architecture: It refers to one of the two major types of network architecture: Peer-to-peer or client/server. In a Peer-to-Peer networking configuration, there is no server, and computers simply connect with each other in a workgroup to share files, printers and Internet access. They are most commonly found in home configurations and are only practical for workgroups of a dozen or fewer computers. In a client/server network there is usually an NT Domain Controller, to which all of the computers log on.

This server can provide various services, including centrally routed Internet Access, mail (including e-mail), file sharing and printer access, as well as ensuring security across the network. This is most commonly found in corporate configurations, where network security is essential.

Read About, Divmod in Python, Swapcase in Python

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Python for Network Programming

Python is syntactically simplest to implement amongst its counterparts. Also, we can do almost everything with python. We can make a website using python. We can also make our own application using Python.

The third-party libraries support provided by python makes it limitless. There is proper documentation for the third-party libraries as well, hence using them in our application becomes easier. So, Python is the perfect choice for network programming.

Python Network Services:

There are two levels of network service access in Python as mentioned below:

  • Low-Level Access
  • High-Level Access

In the first case, programmers can use and access the basic socket support for the operating system using Python’s libraries, and programmers can implement both connection-less and connection-oriented protocols for programming. Application-level network protocols can also be accessed using high-level access provided by Python libraries. These protocols are HTTP, FTP and more.

This article is mostly based on some most famous  fundamental concept of Networking and Socket Programming in Python.

Defination of Sockets: To understand what actually sockets are, we have to firstly have some knowledge about Internet Connection. The Internet Connection basically connects two points across the internet for data sharing and other stuff. One process from computer first can communicate to a process from computer second, over an internet connection.

It has the following properties:

  • Reliable: It means until the cables connecting two computers are safe, data will be transferred safely
  • Point-to-Point: Connection is established between two points
  • Full-Duplex: It means the transfer of information can occur in both ways i.e. from client to simultaneously at the same time

A socket is the end-point in a flow of communication between two programs or communication channels operating over a network. They are created using a set of programming requests called socket API (Application Programming Interface). Python’s socket library offers classes for handling common transports as a generic interface.

Sockets use protocols for determining the connection type for port-to-port communication between client and server machines. The protocols are used for the following:

  • Domain Name Servers (DNS)
  • IP addressing
  • E-mail
  • FTP (File Transfer Protocol)

So, Sockets are the endpoints of a bidirectional, point-to-point communication channel. Given an internet connection, say between the client (a browser) and the server (say codingninjas.com), we will have two sockets a Client Socket and a Server Socket. Socket acts on two parts: IP Address + Port Number. 

IP addresses are the addresses which help to uniquely identify a device over the internet and Port is an endpoint for the communication in an operating system.

Also read,  python filename extensions

Socket Programming in Python

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket or node listens on a particular port at an IP, while 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. Socket programming is started by importing the socket module or framework. This module consists of built-in methods that are required for creating sockets and help them associate with each other.

Some of the important methods of them are as follows:

Methods Description
socket.socket()used to create sockets (required on both server as well as client ends to create sockets)
 socket.accept( )used to accept a connection. It returns a pair of values (conn, address) where conn is a new socket object for sending or receiving data and address is the address of the socket present at the other end of the connection
socket.bind()used to bind to the address that is specified as a parameter
 socket.close()used to mark the socket as closed
socket.connect()used to connect to a remote address specified as the parameter
    socket.listen()enables the server to accept connections

Introduction to Client-Server Programming: Now from the above discussion about the socket modules and understanding the importance of these socket module, let’s take a look on how it can serve to create servers and clients for Socket Programming in Python.

Server: A server is either a program, a computer, or a device that is devoted to managing network resources. Servers can either be on the same device or computer or locally connected to other devices and computers or even remote.  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.

import socket

s = socket.socket()
print("Socket Successfully created")

port = 12345

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('Thank you for connecting')
	c.close()

 

  • First of all, we import the socket which is necessary
  • Then we made a socket object and reserved a port on our PC
  • 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 listen modem, five here means that five connections are kept waiting if the server is busy and if a sixth 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, for this we use the client. A client is either a computer or software that receives information or services from the server. In a client-server module, clients requests for services from servers. The best example is a web browser such as Google Chrome, Firefox, etc. These web browsers request web servers for the required web pages and services as directed by the user.

Programme for client side:

import socket

s = socket.socket()

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

print s.recv(1024)
s.close()

 

  • First of all, we make a socket object
  • Then we connect to localhost on port 12345 (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

To execute these programs, we have to do what? just open our command prompt, get into the folder where we have created our client and server program and then type py  server.py  for server-side in particular prompt and to execute client we have to type py client.py in different command prompt. Once all this is done, the server and client starts running and hence we clearly implement our socket programming.

To explore more about Python programming, read Python Data Structures.

Frequently asked questions

What is socket programming?

Socket programming shows how to use socket APIs to establish communication links between remote and local processes. The socket processes can reside on the same system or different systems on different networks. Sockets are helpful for both stand-alone and network applications.

What are the two types of sockets?

Sockets are basically of two types:

  1. connection-oriented
  2. connectionless. 

How many connections can be in a socket?

The maximum number of sockets allowed per connection between an application and the TCP/IP sockets interface for most socket interfaces is 65535.

Conclusion

This article extensively discussed Network Fundamentals & Socket Programming. 
We hope that this blog has helped you enhance your knowledge regarding socket programming in Python and if you would like to learn more, check out our articles in the code studio library. Do upvote our blog to help other ninjas grow. Happy Coding!

Recommended Readings:

Previous article
Socket Programming In Python
Next article
Multithreading in Python
Live masterclass