Source

Python socket network programming

Hi there fellows. In this post I am going to take you on an adventure with python sockets. They are the real backbones behind web browsing. In simpler terms there is a server and a client. We will deal with the client first. So lets first begin 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. ipv6 requires something different but we won’t be focusing on it. Secondly the SOCK_STREAM means connection oriented TCP protocol. Now we will connect to a server using this socket.

Connecting to a server

Well firstly let me tell you that if any error occurs during the creation of a socket then a socket.error is thrown and secondly we can only connect to a server by knowing it’s ip. You can find the ip of the server by doing this in the command prompt or the terminal:

$ ping www.google.com

You can also find the ip using python:

import socket 

ip = socket.gethostbyname('www.google.com')
print ip

So lets begin with writing our script. In this script we will connect with google. Here’s the code for it:

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 \
on port == %s" %(host_ip)

Now save this script and then run it. You will get something like this in the terminal:

Socket successfully created
the socket has successfully connected to google 
on port == 173.194.40.19

So what did we do here? First of all we made a socket. Then we resolved google’s ip and lastly we connected to google. This was not useful for us though so lets move on. So 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 server can also send data to the client using this function. Now lets make a simple server-client program to see all of this in action and hopefully it will make your concepts more clear.

Making a server

First of all let me explain a little bit about a 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. Next a server has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections. And lastly 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. Now lets begin making our simple server:

# 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. 
   c.send('Thank you for connecting')
   # Close the connection with the client
   c.close()                

So what are we doing here? 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 binded 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 mode. What does 5 mean? It means that 5 connections are kept waiting if the server is busy and if a 6th socket trys to connect then the connection is refused. Lastly 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 have to program a client.

Making a client

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

After typing those commands you will get the following output in your terminal:

# 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 lets make our client:

# 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
print s.recv(1024)
# close the connection
s.close()                     

The above script is self explanatory but still let me explain to the beginners. 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. Was that difficult? I hope not. 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)

$ python client.py
Thank you for connecting

I hope this intro to sockets in python was digestible for beginners. In my server and client script I have not included exception handling as it would have boggled the beginners. Now I hope that you have a solid understanding about the working of sockets in python. However there’s a lot more to it. For further study i recommend the Official python docs and this article on binary tides. If you liked this post then don’t forget to share it on facebook, tweet it on twitter and follow our blog.

You might also like

Newsletter

×

If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I send it out every other month. It contains new stuff that I make, links I find interesting on the web, and occasional discount coupons for my book. Join the 5000+ other people who receive my newsletter:

I send out the newsletter once every other month. No spam, I promise + you can unsubscribe at anytime

✍️ Comments

Michal

Thank you, I’ve been struggling to understand network programming for last 2 days and this is the best and clearest explanation I found on the web.

Yasoob
In reply to Michal

Hi Michal I am glad to hear that :)

mjmokaal

Awesome post… I understood everything you posted

can you please help we with below, don’t need entire script but just helping hands

I am trying something like,

  1. fetch some strings from files and check those patterns in incoming packets on port 80

  2. If patterns found, output like,

Source: IP Pattern: URL:

Example: Source: 198.12.45.87 Pattern: /cgi-bin URL: http://www.example.com/cgi-bin

something like,

pack = s.rec(1024) for incoming packets on port 80

and then each packets captured,

if (“pattern” in pack): print “[Source IP: , Pattern: , URL: “)

Yasoob
In reply to mjmokaal

I will try to reply you once I make it.

cavitacion

Right here is the perfect blog for anyone who really wants to understand this topic. You realize so much its almost hard to argue with you (not that I really will need to…HaHa). You definitely put a fresh spin on a topic that’s been written about for decades. Great stuff, just wonderful!

pizzahutcouponcodes

Fine way of describing, and good post to take facts about my presentation topic, which i am going to convey in university.

amit singh

dude, you saved me. can you please give me a tip on how can i send a file from server to client.

Dan

Hi, great tutorial and very well explained, thankyou!

However I get this error:

s.bind(('', port)) OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

Anyone got any ideas?

mohammed

thank you, i was having a problem regarding closing the server socket, seems like i cannot use the port more than once for the server

Yasoob
In reply to mohammed

You can use it more than once but you can not use in two separate programs at the same time. i.e only one server should be running at any given time. For running the second server along with the first one you need to change the port. I am not sure if this answered your question or not. Feel free to reply me if it has not. :)

Ritwik

Hi can you suggest some changes in the above procedure for IPv6 implementation…

Cantbuymac

Please explain Multi-threading.

emorres25Shaurya

Hey thanks so much! Great for beginners! :)

SamV

Reblogged this on Power to Build and commented: Socket programming in Python?! Visit below link for a Nice post!

Jannis

Can you explain, why we bind the socket to 12345, but the client connects to 52***…

RAVIKEERTHI

I am trying to connect linux machines via telnet. I am able to connect to it and execute the commands (For Ex: “ls”), but I am not able to get the output of “ls” when I try to print it. Using exit I am closing the connection, then only I am able to read all the contents and print on my console.

Can anyone please tel me, how can I fetch the results without closing the connection and execute more commands by using same telnet connection.

Pat Goonetillake

This is the best python socket program help I could find

richierh

I had succeeded to set connection into my local browser and works fine… But how do I close the localhost connections? my browser still connected after I close the script .

Francis Luciano

Great blog you put up. Very informative. However id like to ask you about something else. Is it possible to apply that to two different computers ex connected in LAN. Would it be possible to run a server script and a client script in a server pc and client pc, respectively? And also id like to know if its possible to check if a certain pc is connected to a network or now by any python networking scripts? Thank you for your patience in reading this. Let me know about your answer

Robert Davis

Nice set of tutorial. I like how you explain these topic using common language and terms, You to do not assume that the reader knows technical terms. When basically takes away that whole purpose of a beginner`s tutorial. I would suggest that next you do one on #1 Factories #2 Generators #3 Iterators #4 Tuples #5 Sequences #6 List

Those are topics ( in the of least understood to somewhat understood) that have baffled me in the 16 years that I have been dabbling in python.

harisharan

Dear Yasoob, Please accept love from your old-engineer-brother (73 years) India. You are doing wonderful work of helping the programming mankind . I have gone through your post on Socket Programming in Python. Before this I read many articles on that subject, among all you are the best …. others are so confusing …..please keep it doing . The other area that you might find more interesting …. I suppose you are capable of starting such thing : do something for WORLD-PEACE…peace….peace….the entire mankind is miserably oppressed and living in unrest..unrest….unrest all around the world …. wishing you a peaceful life …

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊

OK