Socket Programming in Python
Last Updated :
28 Feb, 2023
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.
Socket programming is started by importing the socket library and making a simple socket.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address-family ipv4. The SOCK_STREAM means connection-oriented TCP protocol.
Now we can connect to a server using this socket.
Connecting to a server:
Note that if any error occurs during the creation of a socket then a socket. error is thrown and we can only connect to a server by knowing its IP. You can find the IP of the server by using this :
$ ping www.google.com
You can also find the IP using python:
import socket
ip = socket.gethostbyname('www.google.com')
print ip
Here is an example of a script for connecting to Google.
Python3
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except socket.error as err:
print ("socket creation failed with error %s" %(err))
port = 80
try:
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
print ("there was an error resolving the host")
sys.exit()
s.connect((host_ip, port))
print ("the socket has successfully connected to google")
|
Output :
Socket successfully created
there was an error resolving the host
Here when we will be successfully connected the output will be:
Socket successfully created
the socket has successfully connected to google
- First of all, we made a socket.
- Then we resolved google’s IP and lastly, we connected to google.
- Now we need to know how can we send some data through a socket.
- For sending data the socket library has a sendall function. This function allows you to send data to a server to which the socket is connected and the server can also send data to the client using this function.
A 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.
Python3
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'.encode())
c.close()
break
|
- First of all, we import socket which is necessary.
- Then 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 telnet 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
If ‘telnet’ is not recognized. On windows search windows features and turn on the “telnet client” feature.
Output :
# in the server.py terminal you will see
# this output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# In the telnet terminal you will get this:
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Thank you for connectingConnection closed by foreign host.
This output shows that our server is working.
Now for the client-side:
Python3
import socket
s = socket.socket()
port = 12345
s.connect(('127.0.0.1', port))
print (s.recv(1024).decode())
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.
# start the server:
$ python server.py
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# start the client:
$ python client.py
Thank you for connecting
Reference: Python Socket Programming
Similar Reads
Socket Programming in Python
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 serv
6 min read
Simple Calculator in Python Socket Programming
In this article, we are going to know how to make a simple calculator in Python socket programming. Prerequisite: Socket Programming in Python. First, we will understand the basics of Python socket programming. Socket programming is used to set up a communication channel between two nodes on a netwo
4 min read
Getting Started with Python Programming
To get started with Python, let's first finish the installation steps. Here's a basic guide to setup Python in your system. Install PythonBefore starting this Python course first, you need to install Python on your computer. To install Python on your computer, follow these steps: Download Python: Go
2 min read
Socket Programming with Multi-threading in Python
Prerequisite : Socket Programming in Python, Multi-threading in PythonSocket Programming-> It helps us to connect a client to a server. Client is message sender and receiver and server is just a listener that works on data sent by client.What is a Thread? A thread is a light-weight process that d
3 min read
Network Programming Python - HTTP Server
HTTP Web Server is simply a process which runs on a machine and listens for incoming HTTP Requests by a specific IP and Port number, and then sends back a response for the request. Python has a built-in webserver provided by its standard library, can be called for simple client-server communication.
3 min read
Network Programming Python - HTTP Requests
HTTP stands for HyperText Transfer Protocol, which works on the client-server machine. In most cases, the web browser acts as the client, and the computer which hosts the website acts as a server. Python provides the requests module to play with HTTP requests. The requests module plays a major role
2 min read
Python vs Other Programming Languages
Python is a general-purpose, high level programming language developed by Guido van Rossum in 1991. It was structured with an accentuation on code comprehensibility, and its syntax allows programmers to express their concepts in fewer lines of code which makes it the fastest-growing programming lang
4 min read
Python Falcon - Websocket
Websockets provide a powerful mechanism for establishing bidirectional communication between a client and a server over a single, long-lived connection. Python Falcon, a lightweight and fast web framework, offers support for implementing websockets, enabling real-time communication between clients a
3 min read
Network Programming Python - HTTP Clients
The request from the client in HTTP protocol reaches the server and fetches some data assuming it to be a valid request. This response from the server can be analyzed by using various methods provided by the requests module. Some of the ways below provide information about the response sent from the
2 min read
Sockets | Python
What is socket? Sockets act as bidirectional communications channel where they are endpoints of it.sockets may communicate within the process, between different process and also process on different places.Socket Module- s.socket.socket(socket_family, socket_type, protocol=0) socket_family-AF_UNIX o
3 min read
Calling Python from C | Set 2
Prerequisite: Calling Python from C | Set 1 A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module. Cod
3 min read
Calling Python from C | Set 1
In this article, we will mainly focus on safe execution of a Python callable from C, returning a result back to C and writing C code that needs to access a Python function as a callback. The code below focuses on the tricky parts that are involved in calling Python from C. Code #1 : [Step 1 and 2] O
2 min read
Integrating Java with Python
While programming in a language, a developer may feel the need to use some functionality that may have better support in another language. For example, suppose, an application has already been developed in Java, and we wish to use it in Python code. To invoke an existing Java application in Python,
4 min read
Network Scanner in Python
A network scanner is one major tool for analyzing the hosts that are available on the network. A network scanner is an IP scanner that is used for scanning the networks that are connected to several computers. To get the list of the available hosts on a network, there are two basic methods - ICMP Ec
3 min read
Introduction to Python3
Python is a high-level general-purpose programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language make them readable all the time. Note: For more information, refer to P
3 min read
Python - Binding and Listening with Sockets
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 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.
3 min read
Why is Python So Popular?
One question always comes into people's minds Why Python is so popular? As we know Python, the high-level, versatile programming language, has witnessed an unprecedented surge in popularity over the years. From web development to data science and artificial intelligence, Python has become the go-to
7 min read
Multithreading in Python
This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read
Datagram in Python
Datagram is a type of wireless communication between two endpoints and it requires the ip address and port number to establish connection. Datagram uses UDP(User Datagram Protocol), it converts user data into small packets or chunks of data so that it can be sent over a network in a continuous manne
2 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read