Skip to content

Instantly share code, notes, and snippets.

@jflyoo
Created July 24, 2022 17:23
Show Gist options
  • Save jflyoo/d4d25b5e3a54aefce139926be111ede2 to your computer and use it in GitHub Desktop.
Save jflyoo/d4d25b5e3a54aefce139926be111ede2 to your computer and use it in GitHub Desktop.
Use python to create TCP and UDP connections
import socket
target_host = "www.example.com"
target_port = 80
# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the client
client.connect((target_host,target_port))
# send some data
client.send(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
# receive some data
response = client.recv(4096)
print(response.decode())
client.close()
# source:
# Seitz, J., Arnold, T., & Miller, C. A. (2021). Black Hat Python: Python programming for hackers and Pentesters. No Starch Press.
import socket
import threading
IP = '0.0.0.0'
PORT = 9998
def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((IP, PORT))
# start listening with a maximum backlog of connections set to 5
server.listen(5)
print(f'[*] Listening on {IP}:{PORT}')
while True:
client, address = server.accept()
print(f'[*] Accepted connection from {address[0]}:{address[1]}')
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()
def handle_client(client_socket):
with client_socket as sock:
request = sock.recv(1024)
print(f'[*] Received: {request.decode("utf-8")}')
sock.send(b'ACK')
if __name__ == '__main__':
main()
# source:
# Seitz, J., Arnold, T., & Miller, C. A. (2021). Black Hat Python: Python programming for hackers and Pentesters. No Starch Press.
import socket
target_host = "127.0.0.1"
target_port = 9997
# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# send some data
client.sendto(b"Datadatadata",(target_host,target_port))
# receive some data
data, addr = client.recvfrom(4096)
print(data.decode())
client.close()
# source:
# Seitz, J., Arnold, T., & Miller, C. A. (2021). Black Hat Python: Python programming for hackers and Pentesters. No Starch Press.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment