Socket programming in Python
This is a quick guide/tutorial on socket programming in python. Socket programming python is very similar to C.
To summarise the basics, sockets are the fundamental "things" behind any kind of network communications done by your computer.
For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you. Same with any chat client like gtalk or skype.
Any network communication goes through a socket.
In this tutorial we shall be programming Tcp sockets in python. You can also program udp sockets in python.
Coding a simple socket client
First we shall learn how to code a simple socket client in python. A client connects to a remote host using sockets and sends and receives some data.
1. Creating a socket
This first thing to do is create a socket. The socket.socket
function does this.
Quick Example :
#Socket client example in python import socket #for sockets #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket Created'
Function socket.socket
creates a socket and returns a socket descriptor which can be used in other socket related functions
The above code will create a socket with the following properties ...
Address Family : AF_INET (this is IP version 4 or IPv4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Error handling
If any of the socket functions fail then python throws an exception called socket.error which must be caught.
#handling errors in python socket programs import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created'
Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com
Note
Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.
2. Connect to a Server
We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to. So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample.
First get the IP address of the remote host/url
Before connecting to a remote host, its ip address is needed. In python the getting the ip address is quite simple.
import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created' host = 'www.google.com' try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip
Now that we have the ip address of the remote host/system, we can connect to ip on a certain 'port' using the connect function.
Quick example
import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created' host = 'www.google.com' port = 80 try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip
Run the program
$ python client.py Socket Created Ip address of www.google.com is 74.125.236.83 Socket Connected to www.google.com on ip 74.125.236.83
It creates a socket and then connects. Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection. This logic can be used to build a port scanner.
OK, so we are now connected. Lets do the next thing , sending some data to the remote server.
Free Tip
The concept of "connections" apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable "stream" of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by data from other pipes. Another important property of stream connections is that packets have an "order" or "sequence".
Other sockets like UDP , ICMP , ARP dont have a concept of "connection". These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.
3. Sending Data
Function sendall
will simply send data.
Lets send some data to google.com
import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created' host = 'www.google.com' port = 80 try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip #Send some data to remote server message = "GET / HTTP/1.1\r\n\r\n" try : #Set the whole string s.sendall(message) except socket.error: #Send failed print 'Send failed' sys.exit() print 'Message send successfully'
In the above example , we first connect to an ip address and then send the string message "GET / HTTP/1.1\r\n\r\n" to it. The message is actually an "http command" to fetch the mainpage of a website.
Now that we have send some data , its time to receive a reply from the server. So lets do it.
4. Receiving Data
Function recv
is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.
#Socket client example in python import socket #for sockets import sys #for exit #create an INET, STREAMing socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print 'Failed to create socket' sys.exit() print 'Socket Created' host = 'www.google.com'; port = 80; try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip #Send some data to remote server message = "GET / HTTP/1.1\r\n\r\n" try : #Set the whole string s.sendall(message) except socket.error: #Send failed print 'Send failed' sys.exit() print 'Message send successfully' #Now receive data reply = s.recv(4096) print reply
Here is the output of the above code :
$ python client.py Socket Created Ip address of www.google.com is 74.125.236.81 Socket Connected to www.google.com on ip 74.125.236.81 Message send successfully HTTP/1.1 302 Found Location: http://www.google.co.in/ Cache-Control: private Content-Type: text/html; charset=UTF-8 Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=www.google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.www.google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=google.com Set-Cookie: expires=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: path=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: domain=; expires=Mon, 01-Jan-1990 00:00:00 GMT; path=/; domain=.google.com Set-Cookie: PREF=ID=51f26964398d27b0:FF=0:TM=1343026094:LM=1343026094:S=pa0PqX9FCPvyhBHJ; expires=Wed, 23-Jul-2014 06:48:14 GMT; path=/; domain=.google.com
Google.com replied with the content of the page we requested. Quite simple!
Now that we have received our reply, its time to close the socket.
5. Close socket
Function close
is used to close the socket.
s.close()
Thats it.
Lets Revise
So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply
Its useful to know that your web browser also does the same thing when you open www.google.com
This kind of socket activity represents a CLIENT. A client is a system that connects to a remote system to fetch data.
The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.
Now its time to do some server tasks using sockets.
Coding socket servers in Python
OK now onto server things. Servers basically do the following :
1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send
We have already learnt how to open a socket. So the next thing would be to bind it.
1. Bind a socket
Function bind
can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.
Quick example
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete'
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port. There are exceptions to this rule but we shall look into that in some other article.
2. Listen for incoming connections
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function socket_listen
is used to put the socket in listening mode. Just add the following line after bind.
s.listen(10) print 'Socket now listening'
The parameter of the function listen is called backlog. It controls the number of incoming connections that are kept "waiting" if the program is already busy. So by specifying 10, it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected. This will be more clear after checking socket_accept.
Now comes the main part of accepting new connections.
3. Accept connection
Function socket_accept
is used for this.
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' s.listen(10) print 'Socket now listening' #wait to accept a connection - blocking call conn, addr = s.accept() #display client information print 'Connected with ' + addr[0] + ':' + str(addr[1])
Output
Run the program. It should show
$ python server.py Socket created Socket bind complete Socket now listening
So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type
$ telnet localhost 8888
It will immediately show
$ telnet localhost 8888 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host.
And the server output will show
$ python server.py Socket created Socket bind complete Socket now listening Connected with 127.0.0.1:59954
So we can see that the client connected to the server. Try the above steps till you get it working perfect.
We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.
Function sendall
can be used to send something to the socket of the incoming connection and the client should see it. Here is an example :
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' s.listen(10) print 'Socket now listening' #wait to accept a connection - blocking call conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) #now keep talking with the client data = conn.recv(1024) conn.sendall(data) conn.close() s.close()
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
$ telnet localhost 8888 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. happy happy Connection closed by foreign host.
So the client(telnet) received a reply from server.
We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.
It means that a server is supposed to be running all the time. After all its a server meant to serve.
So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept
in a loop so that it can receive incoming connections all the time.
4. Live Server - accepting multiple connections
So a live server will be alive always. Lets code this up
import socket import sys HOST = '' # Symbolic name meaning all available interfaces PORT = 5000 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' s.listen(10) print 'Socket now listening' #now keep talking with the client while 1: #wait to accept a connection - blocking call conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) data = conn.recv(1024) reply = 'OK...' + data if not data: break conn.sendall(reply) conn.close() s.close()
We havent done a lot there. Just put the socket_accept in a loop.
Now run the server program in 1 terminal , and open 3 other terminals.
From each of the 3 terminal do a telnet to the server port.
Each of the telnet terminal would show :
$ telnet localhost 5000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. happy OK .. happy Connection closed by foreign host.
And the server terminal would show
$ python server.py Socket created Socket bind complete Socket now listening Connected with 127.0.0.1:60225 Connected with 127.0.0.1:60237 Connected with 127.0.0.1:60239
So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program. All telnet terminals would show "Connection closed by foreign host."
Good so far. But still the above code does not establish an effective communication channel between the server and the client.
The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time.
So now its time to handle the connections, and handle multiple connections together.
5. Handling Multiple Connections
To handle every connection we need a separate handling code to run along with the main server accepting connections. One way to achieve this is using threads.
The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
We shall now use threads to create handlers for each connection the server accepts.
import socket import sys from thread import * HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' #Bind socket to local host and port try: s.bind((HOST, PORT)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' #Start listening on socket s.listen(10) print 'Socket now listening' #Function for handling connections. This will be used to create threads def clientthread(conn): #Sending message to connected client conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string #infinite loop so that function do not terminate and thread do not end. while True: #Receiving from client data = conn.recv(1024) reply = 'OK...' + data if not data: break conn.sendall(reply) #came out of loop conn.close() #now keep talking with the client while 1: #wait to accept a connection - blocking call conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function. start_new_thread(clientthread ,(conn,)) s.close()
Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.
The telnet terminals would show :
$ telnet localhost 8888 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Welcome to the server. Type something and hit enter hi OK...hi asd OK...asd cv OK...cv
The server terminal might look like this
$ python server.py Socket created Socket bind complete Socket now listening Connected with 127.0.0.1:60730 Connected with 127.0.0.1:60731
The above connection handler takes some input from the client and replies back with the same.
So now we have a server thats communicative. Thats useful now.
Conclusion
By now you must have learned the basics of socket programming in python. You can try out some experiments like writing a chat client or something similar.
When testing the code you might face this error
Bind failed. Error Code : 98 Message Address already in use
When it comes up, simply change the port number and the server would run fine.
If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.
Perfect!
Well explained post. Thanks. However, I have a condition where the client hangs on the connection even after the receiving the response. I have checked and ensured that all connections are closed after response is given back to the client.
Hi, thanks for this great tutorial, I just have one question.
When I enter a letter into the cmd console the program doesn’t wait for the enter key to be pressed, it automatically returns the “OK .. ” message with the first key I press. I have searched for an answer on the internet but without success. Can anyone help please?
Ian
Awesome…
very helpful article…
keep doing this
I can’t get a terminal that can connect to the server with $ telnet localhost 8888. Any suggestions?
Hi, Perfect example! One question – suggestion only:
How can I add a timeout for each of the thread?
If a client is inactive for 60 seconds the server must disconnect him.
Thank you!
Thank you for this! This was super helpful–I’ve never written server code before!!!
It’s people like you who help the dreamers manifest their visions.
Thanks.
what are return values in accept call i.e conn, addrs ?? what are the values contained in those parameters??
I tried to learn socket programming from different tutorials and website but tutorial from this website is very very good…….Thank you….
Really, Very Help Articles.
But If Anyone Wants More Example,
Check Here : https://bitforestinfo.blogspot.com/2017/03/how-to-create-simple-tcpip-server-and.html
Such a simple but totally helpful tutorial. Made my server app work first time.
thx! it helps me a lot! Expect more interesting articles
First sockets tutorial where things finally clicked for me! Very clear and easy to understand, thanks so much.
Same for me. This tutorial did a better job then by Prof. This is a great start.
Thanks.
Great work man.Keep making videos about python network programming.Really helpful
oh, and a small mod here to make the connection close and release the port quickly.. I added a shutdown as follows
s.shutdown(socket.SHUT_RDWR)
s.close()
Thank you so much for this amazing clear tutorial. It was a great help to me!
This helped me alot, any explanation as to why AF_INET and SOCK_STREAM are capitalised?
That’s just the way the variables are named.
Normally variables which value doesn’t change (so called constants) are written ALL_CAPITALIZED.
Cheers.
simple and useful, thanks a lot.
great help. I still have one question, after I quite the thread loop , always get error in main thread
Unhandled exception in thread started by
Traceback (most recent call last):
File “D:\code\Learn\python\mySocketServer.py”, line 26, in clientthread
data = conn.recv(1024)
socket.error: [Errno 10053]
my code like this:
def clientthread(conn):
#Send message to connected client
conn.send(‘Welcome to the server, type bye to quit’)
run = True
while run:
#Receiving from client
data = conn.recv(1024)
reply = ‘OK…..’ + data
if data ==’bye’:
conn.close()
return
else:
conn.sendall(reply)
what if i need concurrency and 1000k plus concurrent clients ? any suggestions what to use with python itself …this is an IOT project along with android users….
Excellent step by step approach!
No unnecessary complicated command. GREAT!
in Handling Connections section
start_new_thread(clientthread ,(conn,))
you should replace with
thread.start_new_thread(clientthread ,(conn,))
Did you not see how he imported the thread module
Because code is using this statement –
from thread import *
it’s fetching all available methods of thread class into current script.
Therefore you don’t need to write –
thread.start_new_thread()
I hope it clears the confusion.
Thank you !
Silver, thank you so much for contributing such a comprehensive article, i am new to socket programming nut enjoy a lot by reading your article and programming the code.
excellent tutorial
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
I suggest to add this line if you dont want to change the port manually every time
Just set the option and the system will know that the port could be reused
love it
data = s.recv(1024)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
getting this error every time
i am running python 3.4
Very good step-by-step tutorial. You’re a good instructor. Thank you
Are there any tutorials for commands list, get, wiseget?
Thanks
Dude I love you srsly, but I have a question. How can I modify this code to send files from a client to the server? Thanks a lot!
Thanks . This was great and very helpful
awesome tutorial.first time got satisfied with the programming tutorials
gr8 tutorial thank you very much m8 – just straight forward, very good explained – nothing uneccesary
are your examples cross-platforms?
if not data:
break
I think this can be never touched.
very well thank you.
very cool. Thanks for sharing..
Thank you for this great tutorial!
Hey Man, Thanks . I completely fell in love with your page that i didn’t want to close it.
Nice design and i love how you took the lesson step by step. I haven’t learnt something so fast like how i learnt your lesson
Learnt… Help us all.
Awesome post!! Thank you.
I am writing code in python for a chat client.H
ow do i broadcast a message to all connected computers in the network? or get a list of all connected ip’s?
I tried the above example…it worked but when i use data = conn.recv(1024) and send data…i see output as connected with 127.0.0.1:57721 but no change after tat…it stands still ..i dont understand
Super…. clear Explanation…I love it…keep it up…
I’m using Python 3.4.1, can you share the code snippet for both server.py and client.py file?
You could explain basic difference between TCP (reliable delivery of an ordered stream of bytes) and UDP (best-effort delivery of individual messages).
If this server was running on a MAC, how would you connect to it on a Windows machine
There is no difference at the basic level. Byte ordering is an advanced topic and only affects communications between big-endian and little-endian machines. You can google that.
I run the last version (with handling connections). When all of three telnet connections opened in other terminals are closed main program (server) is still running. It’s because of while loop, but how to finish the program efficiently? I mean, how to make it stop?
Great post, very helpful and had me understanding how to write a client and server in under an hour. Thank you very much for posting this.
Good article! Thanks!