Socket programming in python

Python Socket:

To summarise the basics, sockets are the fundamental “things” behind any kind of network communications done by your computer. For example when you type http://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.

Connect to Remote Host

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


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.

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 http://www.google.com is 74.125.236.83
Socket Connected to http://www.google.com on ip 74.125.236.83

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.

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
About these ads

One thought on “Socket programming in python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s