Setting basic client with the socket module

Setting basic client with the socket module

Shebang and Importing Modules

Python
#!/usr/bin/python

import socket

Creating and Connecting the Socket

Python
print('creating socket ...')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket created')
print("connection with remote host")

Setting Target Host and Port

Python
target_host = "www.awjunaid.com" 
target_port = 80

Establishing Connection

Python
s.connect((target_host, target_port))
print('connection ok')

Sending HTTP Request

Python
request = "GET / HTTP/1.1\r\nHost:%s\r\n\r\n" % target_host
s.send(request.encode())

Receiving and Printing Data

Python
data = s.recv(4096)
print("Data", str(bytes(data)))
print("Length", len(data))

Closing the Socket

Python
print('closing the socket')
s.close()
Python
#!/usr/bin/python

import socket

print('creating socket ...')
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('socket created')
print("connection with remote host")

target_host = "www.awjunaid.com" 
target_port = 80

s.connect((target_host,target_port))
print('connection ok')

request = "GET / HTTP/1.1\r\nHost:%s\r\n\r\n" % target_host
s.send(request.encode())

data=s.recv(4096)
print("Data",str(bytes(data)))
print("Length",len(data))

print('closing the socket')
s.close()

This script demonstrates a basic interaction with a web server by establishing a TCP connection, sending an HTTP request, receiving the response, and then closing the socket. Keep in mind that this script is a simplified example and may not handle all edge cases or errors that could occur in a real-world scenario.

Exit mobile version