Shebang and Importing Modules
Python
#!/usr/bin/python
import socket- Shebang: Specifies the Python interpreter to be used when the script is executed.
- Importing Modules: Imports the
socketmodule for working with sockets.
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")- Creating Socket: Creates a TCP socket using
socket.AF_INETfor IPv4 andsocket.SOCK_STREAMfor a stream-oriented connection (TCP). - Print Statements: Outputs messages indicating the socket creation and connection process.
Setting Target Host and Port
Python
target_host = "www.awjunaid.com"
target_port = 80- Setting Target Host and Port: Defines the target host (in this case, any website) and the target port (HTTP port 80).
Establishing Connection
Python
s.connect((target_host, target_port))
print('connection ok')- Establishing Connection: Connects the socket to the specified target host and port.
- Print Statement: Outputs a message indicating a successful connection.
Sending HTTP Request
Python
request = "GET / HTTP/1.1\r\nHost:%s\r\n\r\n" % target_host
s.send(request.encode())- Building HTTP Request: Constructs a simple HTTP GET request for the root path (“/”) using HTTP/1.1 and includes the
Hostheader. - Sending Request: Sends the encoded request to the connected server.
Receiving and Printing Data
Python
data = s.recv(4096)
print("Data", str(bytes(data)))
print("Length", len(data))- Receiving Data: Receives data (up to 4096 bytes) from the server.
- Print Statements: Outputs the received data as a string and its length.
Closing the Socket
Python
print('closing the socket')
s.close()- Closing the Socket: Closes the socket to release the resources.
- Print Statement: Outputs a message indicating the closure of the socket.
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.
Thanks for sharing this idea Anita