Add example for python sockets

This commit is contained in:
Mia von Steinkirch 2020-02-19 14:20:40 -08:00
parent 54c2782f9c
commit 3a4a977fed
7 changed files with 116 additions and 0 deletions

View file

@ -0,0 +1,6 @@
# Medium Examples
This directory holds any code and snippet that I have published in Medium:
* [Learn Networking with Pythons Socket and Threading Module 🚀](https://medium.com/python-for-the-utopian/learning-networking-with-pythons-socket-and-threading-module-30dc77e1fc59).

View file

@ -0,0 +1,6 @@
import socket
HOST = 'www.github.com'
PORT = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

View file

@ -0,0 +1,26 @@
import socket
PORT = 12345
HOSTNAME = '54.209.5.48'
def netcat(text_to_send):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOSTNAME, PORT))
s.sendall(text_to_send)
s.shutdown(socket.SHUT_WR)
rec_data = []
while 1:
data = s.recv(1024)
if not data:
break
rec_data.append(data)
s.close()
return rec_data
if __name__ == '__main__':
text_to_send = ''
text_recved = netcat( text_to_send)
print(text_recved[1])

View file

@ -0,0 +1,11 @@
DATA = 'GET / HTTP/1.1\r\nHost: google.com\r\n\r\n'
def tcp_client():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
client.send(DATA)
response = client.recv(4096)
print(response)
if __name__ == '__main__':
tcp_client()

View file

@ -0,0 +1,33 @@
import socket
import threading
BIND_IP = '0.0.0.0'
BIND_PORT = 9090
def handle_client(client_socket):
request = client_socket.recv(1024)
print(f'[*] Received: {request}')
client_socket.send('ACK')
client_socket.close()
def tcp_server():
server = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
server.bind(( BIND_IP, BIND_PORT))
server.listen(5)
print(f'[*] Listening on {BIND_IP}, {BIND_PORT}')
while 1:
client, addr = server.accept()
print(f'[*] Accepted connection: {addr[0]}:{addr[1]}')
client_handler = threading.Thread(target=handle_client, args= (client,))
client_handler.start()
if __name__ == '__main__':
tcp_server()

View file

@ -0,0 +1,16 @@
import socket
HOST = '127.0.0.1'
PORT = 9000
DATA = 'AAAAAAAAAA'
def udp_client():
client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(DATA, ( HOST, PORT ))
data, addr = client.recvfrom(4096)
print(data, adr)
if __name__ == '__main__':
udp_client()

View file

@ -0,0 +1,18 @@
import socket
BIND_IP = '0.0.0.0'
BIND_PORT = 9000
def udp_server():
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(( BIND_IP, BIND_PORT))
print(f'Waiting on port: {str(BIND_PORT)}')
while 1:
data, addr = server.recvfrom(1024)
print(data)
if __name__ == '__main__':
udp_server()