Python Network Programming - GeeksforGeeks

19 Oct, 2021
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.
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 have their own set of vocabulary, let’s have a look at them – 
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 “<brodcast>”
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.
These methods are used on the server-side. Let’s see each method in detail – 
This method is used on the client side. Let’s see this method in detail – 
These are the general methods of the socket module. Let’s see each method in detail.
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
# first of all import the socket libraryimport socket  # next create a socket objects = socket.socket()print ("Socket successfully created")  # reserve a port on your computer in our# case it is 40674 but it can be anythingport = 40674  # Next bind to the port# we have not typed any ip in the ip field# instead we have inputted an empty string# this makes the server listen to requests# coming from other computers on the networks.bind(('', port))print ("socket binded to %s" %(port))  # put the socket into listening modes.listen(5)    print ("socket is listening")  # a forever loop until we interrupt it or# an error occurswhile True:      # Establish connection with client.    c, addr = s.accept()    print ('Got connection from', addr )      # send a thank you message to the client.    c.send(b'Thank you for connecting')      # Close the connection with the client    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.
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 :
In the telnet terminal you will get this:
This output shows that our server is working. Now for the client-side: 
Example: Network Programming Client Side
Python3
# Import socket moduleimport socket  # Create a socket objects = socket.socket()  # Define the port on which you want to connectport = 40674  # connect to the server on local computers.connect(('127.0.0.1', port))  # receive data from the serverprint(s.recv(1024))  # close the connections.close()
Output:
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
Python-Networking
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | os.path.join() method
Python | Get unique values from a list