hii readers, This Is Our second Post about python Socket Programming. So, In This Article, I Am Going To Show You how to create a simple client python script using python socket module.
In this article,
we will see how we can simply interact with websites using python socket module.
so, let's start but first,
i will suggest you to read Python Socket Programming - Part 1
because in first part, i describe about socket function and many basic things.
so,let's start today's tutorial
Here,
first import module
then, select host and port
create socket object
#!/usr/bin/python
# Import Modules
import socket
import sys
# Host Server Configurations
host = 'www.google.com'
port = 80
# Creating Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print '[+] Socket Created -> Done'
In Second Part
get host ip address
bind client with server
# First, For Connection, We need Host ip. so,
# Get Host IP Address
host_ip = socket.gethostbyname(host)
#Connect to remote server
s.connect((host_ip , port))
# print conformation message
print '[+] Socket Connection Established : \n\t\tHost : {} | IP : {} '.format(host,host_ip)
In Third Part
send message to server
and
receive message from server
#Send some data to remote server
message = "GET / HTTP/1.1\r\n\r\n"
s.sendall(message)
print 'Message send successfully'
#Now receive data
reply = s.recv(1024)
# print message received
print reply
# Close Socket
s.close()
And,
write complete code
Finally,
#!/usr/bin/python
# Import Modules
import socket
import sys
# Host Server Configurations
host = 'www.google.com'
port = 80
# Creating Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print '[+] Socket Created -> Done'
# First, For Connection, We need Host ip. so,
# Get Host IP Address
host_ip = socket.gethostbyname(host)
#Connect to remote server
s.connect((host_ip , port))
# print conformation message
print '[+] Socket Connection Established : \n\t\tHost : {} | IP : {} '.format(host,host_ip)
#Send some data to remote server
message = "GET / HTTP/1.1\r\n\r\n"
s.sendall(message)
print 'Message send successfully'
#Now receive data
reply = s.recv(1024)
# print message received
print reply
if "Location" in reply:
pass
else:
# Socket Close
s.close()
# Exit
sys.exit(0)
# Extracting Header From Received Message Data
header = reply[:reply.find('\r\n\r\n')]
# Handling Redirections
header_lnie_starting_point = header.find('Location')
# Extract Location Line From Header
header = header[header_lnie_starting_point:]
# Header location line
location_line = header.split('\n')[0]
# Get New Address
new_adderr = location_line[location_line.find(":")+2:]
print "[+] Redirecting Url Found : {}".format(new_adderr)
# Socket Close
s.close()
let run these code and check output
here, i got these error
[+] Socket Created -> Done
[+] Socket Connection Established :
Host : www.google.com | IP : 74.125.130.106
Message send successfully
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.in/?gfe_rd=cr&ei=6N7DWOe6HdelvwTTzLKYDQ
Content-Length: 261
Date: Sat, 11 Mar 2017 11:26:32 GMT
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.in/?gfe_rd=cr&ei=6N7DWOe6HdelvwTTzLKYDQ">here</A>.
</BODY></HTML>
[+] Redirecting Url Found : http://www.google.co.in/?gfe_rd=cr&ei=6N7DWOe6HdelvwTTzLKYDQ
As, You Can See, Our Client Is Now Ready!
So, Let's Move Ahead
and
let revise again to create server script
# step 4 :
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
# print server address and port
print "[+] Server IP {} | Port {}".format(server_address[0],server_address[1])
# bind socket with server
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
# Create Loop
while True:
# Wait for a connection
print '[+] Waiting for a client connection'
# connection established
connection, client_address = sock.accept()
try:
print '[+] Connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print 'received "%s"' % data
if data:
print 'sending data back to the client'
connection.sendall(data)
else:
print 'no more data from', client_address
break
finally:
# Close the connection
connection.close()
here,
my server output is
[+] Server IP localhost | Port 10000
[+] Waiting for a client connection
[+] Connection from ('127.0.0.1', 53782)
received "This is the mess"
sending data back to the client
received "age. It will be"
sending data back to the client
received " repeated."
sending data back to the client
received ""
no more data from ('127.0.0.1', 53782)
[+] Waiting for a client connection
I Think,
This is enough for today. So, readers In MY Next Tutorial You Will See More Useful Examples and codes.
For More Details about socket :
Reference Links :
Python Official SiteAnd :
pymotw
If You Like My Article,
Like, Comment, Share.
Written By :
Suraj
More Update, Visit Our Regularly.
And Subscribe Our Blog,
Follow Us and share it.
For Any Type of Suggestion Or Help
Contact me:
Suraj
surajsinghbisht054@gmail.com