Tuesday, March 18, 2014

Connecting to a Server using Python Sockets.

Alright, alright, alright...

Below is a small python script to create a python socket and connect to http://google.com and print the response.

You need to follow the following steps

1. Specify the host and port number to which you want to connect. For HTTP protocol, the port no. is 80.

2. Create a socket which accepts address in the format AF_INET (IP and port)  and connection of the form SOCK_STREAM ( TCP stream connection - this is how you normally connect to a website)

3.  Now we find the IP address of http://google.com .

4.  Store the GET request in a string and we will send this string as a message to the server. A server is a machine and it understands your message only when you send it in a particular format. A browser sends a GET request to fetch the contents of a webpage.

5.  Now that we have our socket, IP address, port, GET request message ready, we simply connect to the server.

6. The server naturally understands the GET requests and sends the webpage as a response.

7. For our purpose, we just receive only 1024 bytes and discard the rest.

8. Print the response received on the screen.
import socket             #to import the socket module

host="www.google.com"     #we will connect to this host

port=80                   # we will connect to HTTP port 80

s1=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

'''This statement creates the socket and the Parameter AF_INET indicates the Address Family which will be used to specify the address, for AF_INET the address the format is a (host,port) pair. SOCK_STREAM parameter indicates that we want to create a TCP connection.'''

ip_add=socket.gethostbyname(host)      

#this function gets the IP address of host

s1.connect((ip_add,port))                       

#now we connect using (host,port) pair which is in AF_INET format

get_req="GET / HTTP/1.1\r\n\r\n"

''' This is the format of a simple get request. A browser also sends a GET request when you type www.google.com in the address bar '''

s1.sendall(get_req)       

#This sends the GET request string to the server.

reply=s1.recv(1024)     

#This receives 1024 bytes from the server

print(reply)                    

#This prints the results on screen

s1.close()

#This closes the socket