Change language

Socket programming in Python


Socket programming starts by importing a socket library and creating a simple socket.

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

Here we made a socket instance and passed two parameters to it. The first parameter —  AF_INET, and the second —  SOCK_STREAM . AF_INET belongs to the ipv4 address family. SOCK_STREAM stands for connection oriented TCP.

We can now connect to the server using this socket.

Connecting to the server:
Please Note that if any error occurs during socket creation, socket.error is thrown and we can connect to the server only knowing that it is ip. You can find the IP address of the server using this:

 $ ping 

You can also find the IP using Python:

 import socket ip = socket.gethostbyname (’’) print ip 

Here is an example script to connect to Google


 Socket successfully created the socket has successfully connected to google on port == 
  • First of all we made an outlet.
  • Then we solved the IP address of Google and finally we connected to Google.
  • Now we need to know how we can send some data via socket.
  • The socket library has a sendall function to send data. This function allows you to send data to the server to which the socket is connected, and the server can also send data to the client using this function.

Simple server-client program:

The server has a bind () method that binds it to a specific ip and port so that it can listen for incoming requests to that ip and port. The server has a listen () method that puts the server into listening mode. This allows the server to listen for incoming connections. Finally, the server has accept () and close () methods. The accept method initiates a connection to the client, and the close method closes the connection to the client.

# Example script to connect to Google using a socket
# Python programming

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 socket port

port = 80


try :

host_ip = socket.gethostbyname ( ’’ )

except socket.gaierror:


# this means that failed to resolve host

print " there was an error resolving the host "

  sys.exit ()

# connect to server
s.connect ((host_ip, port))


print "the socket has successfully connected to google

on port = = % s "  % (host_ip)

# first of all import the socket library

import socket 

# then create a socket object

s = socket.socket () 

print "Socket successfully created"

# reserve a port on your computer in our
# happens 12345 but can be anything

port = 12345  

< code class = "undefined spaces">  
# Next port binding
# we didn’t enter ip in the ip field
# instead we entered an empty line
# this makes the server listen for requests
# coming from other computers on the network
s.bind ((’’, port)) 

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

# put socket in listening mode

s.listen ( 5

print "socket is listening"  

# forever th cycle until we interrupt it or
# an error occurs

while True :


# Contact customer.

c, addr = s.accept () 

print ’Got connection from’ , addr


  # send a thank you message to the client.

c.send ( ’ Thank you for connecting’ )


# Close client connection

c.close ()

  • First of all we import the socket we need.
  • Then we created a socket object and reserved a port on our computer.
  • After that we bind our server to the specified port. Passing an empty string means that the server can also listen for incoming connections from other computers. If we had passed, it would only listen to calls that were made on the local computer.
  • After that, we put the server into listening mode. 5 here means 5 connections are pending if the server is busy and if the 6th socket tries to establish a connection then the connection is rejected.
  • Finally, we do a while loop and start accepting all incoming connections and close these connections after a thank-you message to all connected sockets.

Now we need something the server can communicate with. We could send a request to the server to find out that our server is running. Enter these commands in a terminal:

 # start the server $ python 

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

 $ telnet localhost 12345 


 # in the terminal you will see # this output: Socket successfully created socket binded to 12345 socket is listening Got connection from (’’, 52617) 
 # In the telnet terminal you will get this: Trying :: 1 ... Trying ... Connected to localhost ... Escape character is ’^]’. Thank you for connectingConnection closed by foreign host. 

This output shows that our server is running.

Now for the client side:

# Import a socket module

import socket 

# Create socket object

s = socket.socket () 

# Define the port you want to connect to

port = 12345  

# connect to server on local computer

s.connect (( ’127.0 .0.1’ , port))

# receive data from the server

print s.recv ( 1024 )

# close connection
s.close () 

  • First of all, we make a socket object.
  • Then we connect to the localhost on port 12345 (the port our server is running on) and finally get data from the server and close the connection.
  • Now save this file as and run it from the terminal after running the server script.
 # start the server: $ python Socket successfully created socket binded to 12345 socket is listening Got connection from (’’, 52617) 
 # start the client: $ python Thank you for c onnecting 

Link: Python Socket Programming

This article courtesy of Kishlai Verma . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See my article appearing on the Python.Engineering homepage and help other geeks.

Please write in comments if you find anything wrong or if you’d like to share more information on the topic discussed above.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


Common xlabel/ylabel for matplotlib subplots

12 answers


How to specify multiple return types using type-hints

12 answers


Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers


Flake8: Ignore specific warning for entire file

12 answers


glob exclude pattern

12 answers


How to avoid HTTP error 429 (Too Many Requests) python

12 answers


Python CSV error: line contains NULL byte

12 answers


csv.Error: iterator should return strings, not bytes

12 answers



Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python


How to specify multiple return types using type-hints


Printing words vertically in Python


Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries


Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically