Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctrngk/0f9dae1010cf689f92d2b4658031d3e5 to your computer and use it in GitHub Desktop.
Save ctrngk/0f9dae1010cf689f92d2b4658031d3e5 to your computer and use it in GitHub Desktop.
Python TCP Client Server Example
import socket
hostname, sld, tld, port = 'www', 'integralist', 'co.uk', 80
target = '{}.{}.{}'.format(hostname, sld, tld)
# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the client
# client.connect((target, port))
client.connect(('0.0.0.0', 9999))
# send some data (in this case a HTTP GET request)
client.send('GET /index.html HTTP/1.1\r\nHost: {}.{}\r\n\r\n'.format(sld, tld))
# receive the response data (4096 is recommended buffer size)
response = client.recv(4096)
print response
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5) # max backlog of connections
print 'Listening on {}:{}'.format(bind_ip, bind_port)
def handle_client_connection(client_socket):
request = client_socket.recv(1024)
print 'Received {}'.format(request)
client_socket.send('ACK!')
client_socket.close()
while True:
client_sock, address = server.accept()
print 'Accepted connection from {}:{}'.format(address[0], address[1])
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,) # without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject
)
client_handler.start()
@ctrngk
Copy link
Author

ctrngk commented Feb 11, 2020

#!/usr/bin/env python3
# https://gist.github.com/ctrngk/0f9dae1010cf689f92d2b4658031d3e5
# similar to
# curl ifconfig.co/json
import socket

method = 'GET'
port = 80
target = 'ifconfig.co'
path = '/json'
# target, path = 'api.ipify.org', '/'
# target, path = 'ipecho.net', '/plain'
address = (target, port)

# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect the client
client.connect(address)

# send some data (in this case a HTTP GET request)
client.send(f'{method} {path} HTTP/1.1\r\nHost: {target}\r\n\r\n'.encode())

# receive the response data (4096 is recommended buffer size)
response: bytes = client.recv(4096)
print(response.decode())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment