The Wayback Machine - https://web.archive.org/web/20241004220814/https://www.geeksforgeeks.org/socket-programming-python/
Open In App

Socket Programming in Python

Last Updated : 28 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




# An example script to connect to Google using socket
# programming in Python
import socket # for 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))
 
# default port for socket
port = 80
 
try:
    host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
 
    # this means could not resolve the host
    print ("there was an error resolving the host")
    sys.exit()
 
# connecting to the server
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




# first of all import the socket library
import socket            
 
# next create a socket object
s = socket.socket()        
print ("Socket successfully created")
 
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345               
 
# 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 network
s.bind(('', port))        
print ("socket binded to %s" %(port))
 
# put the socket into listening mode
s.listen(5)    
print ("socket is listening")           
 
# a forever loop until we interrupt it or
# an error occurs
while True:
 
# Establish connection with client.
  c, addr = s.accept()    
  print ('Got connection from', addr )
 
  # send a thank you message to the client. encoding to send byte type.
  c.send('Thank you for connecting'.encode())
 
  # Close the connection with the client
  c.close()
   
  # Breaking once connection closed
  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 module
import socket            
 
# Create a socket object
s = socket.socket()        
 
# Define the port on which you want to connect
port = 12345               
 
# connect to the server on local computer
s.connect(('127.0.0.1', port))
 
# receive data from the server and decoding to get the string.
print (s.recv(1024).decode())
# close the connection
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

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 network. It provides Inter connected communication (IPC
4 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 does not require much memory overhead, they are che
3 min read
File Transfer using TCP Socket in Python
In this article, we implement a well-known Protocol in Computer Networks called File Transfer Protocol (FTP) using Python. We use the TCP Socket for this, i.e. a connection-oriented socket. FTP (File Transfer Protocol) is a network protocol for transmitting files between computers over Transmission Control Protocol/Internet Protocol (TCP/IP) connec
4 min read
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Python - Fastest Growing Programming Language
There was a time when the word "Python" meant a particularly large snake but now it is a programming language that is all the rage!!! According to the TIOBE Index, Python is the fourth most popular programming language in the world currently and this extraordinary growth is only set to increase as observed by Stack Overflow Trends. So the question
5 min read
Difference between Python and Lua Programming Language
Python Python is one of the most popular and powerful scripting languages that works nowadays. It is a high-level interpreted programming language. It is a very simple scripting language and very easy to learn as compared to other languages. Python programming language is best for both scripting applications and as standalone programs along with th
3 min read
Programming Paradigms in Python
Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solve the problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming languages that are
4 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Comparison of Python with Other Programming Languages
Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation of programs which makes it the fastest-growing programming language in current times. Python has various other advantages which give it an edge over other popular programming languages su
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
How to Create a Programming Language using Python?
In this article, we are going to learn how to create your own programming language using SLY(Sly Lex Yacc) and Python. Before we dig deeper into this topic, it is to be noted that this is not a beginner's tutorial and you need to have some knowledge of the prerequisites given below. PrerequisitesRough knowledge about compiler design.Basic understan
7 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 language in current times. Features of PythonEasy to c
4 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 server to the Python program running on the clien
2 min read
Incremental Programming in Python
In incremental systems, every measurement refers to a previously dimensioned position (point-to-point). Incremental dimensions are the distances between two adjacent points. An incremental movement moves A distance based on your current position. Start Small - First of all, start your program small and kept that working instead of writing many line
2 min read
Draw house using Turtle programming in Python
Prerequisite: Turtle Programming in Python “Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! ”turtle” comes packed with the standard Python package and need not be installed externally. Step 1: Import turtle and math module in Python. import turtle import math Step 2: Choose a background color fo
2 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. The http.server and socketserver are the two main
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 in HTTP requests, apart from simple request and th
2 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 min read
8 Tips For Object-Oriented Programming in Python
OOP or Object-Oriented Programming is a programming paradigm that organizes software design around data or objects and relies on the concept of classes and objects, rather than functions and logic. Object-oriented programming ensures code reusability and prevents Redundancy, and hence has become very popular even in the fields outside software engi
6 min read
Hybrid Programming using Python and Dart
Hybrid programming is a programming approach that combines different programming paradigms or styles in a single application. It involves using elements from both object-oriented programming and functional programming, for example, or mixing imperative programming with declarative programming. It is possible to use both Dart and Python in a single
4 min read
Getting Started with Competitive Programming in Python
Python is a great option for programming in Competitive Programming. First off, its easy-to-understand and concise grammar enables quicker development and simpler debugging. The huge standard library of Python offers a wide range of modules and functions that can be used to effectively address programming difficulties. Python also offers dynamic ty
11 min read
Which Python Modules are useful for competitive programming?
In the previous article, we have discussed that C++, Java and Python are three most common languages for competitive programming. In this article, we are going to focus on the most important Python modules from competitive programming and interview preparation point of view. list : Dynamic Sized Array that allows insertions and deletions without ca
3 min read
Python Input Methods for Competitive Programming
Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it's 5x. To improve the speed of code execution for input/output intensive problems, languages have
6 min read
Command Line Interface Programming in Python
This article discusses how you can create a CLI for your python programs using an example in which we make a basic "text file manager". Let us discuss some basics first. What is a Command Line Interface(CLI)? A command-line interface or command language interpreter (CLI), also known as command-line user interface, console user interface, and charac
7 min read
How to Setup VSCode with C, C++ and Python for Competitive Programming
VSCode is a Text editor that provides support for development operations and version control systems. It provides tools for a user to build hassle-free codes. VSCode can be downloaded and installed from visualstudio.com This article will show you how to, fetch test cases directly from the browser without copy-pasting and run them in VSCode with jus
5 min read
CGI Programming in Python
What is CGI? Common Gateway Interface (also known as CGI) is not a kind of language but just a specification(set of rules) that helps to establish a dynamic interaction between a web application and the browser (or the client application). The CGI programs make possible communication between client and web servers . Whenever the client browser send
5 min read
Turtle Programming in Python
“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Commonly used turtle methods are : MethodParameterDescriptionTurtle()NoneCreates and returns a new turtle objectforward()amountMoves the turtle f
5 min read
What are the Minimum Hardware Requirements for Python Programming?
Python, as a programming language, has been in use due to its simplicity, readability, and versatility. It is put to wide use in web development, data science, automation, machine learning, and many more. Python is easy to learn, which makes it an excellent choice for beginners; at the same time, its libraries and frameworks make it very powerful f
10 min read
Getting Started with Python Programming
Python is a high-level, interpreted, and general-purpose programming language. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability and simplicity, making it an excellent language for beginners and experienced developers. Getting Started with Python is easy due to its straightforward syntax and extensive
9 min read
Article Tags :
Practice Tags :