TCP/UDP Client

TCP Client

import socket

target_host = "www.google.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: google.com\r\n\r\n")

# receive some data
response = client.recv(4096)

print(response.decode())
client.close()

We first create a socket object with the AF_INET and SOCK_STREAM parameters 1. The AF_INET parameter indicates we’ll use a standard IPv4 address or hostname, and SOCK_STREAM indicates that this will be a TCP client. We then connect the client to the server 2 and send it some data as bytes 3. The last step is to receive some data back and print out the response 4 and then close the socket. This is the simplest form of a TCP client, but it’s the one you’ll write most often.

UDP Client

As you can see, we change the socket type to SOCK_DGRAM1 when creating the socket object. The next step is to simply call sendto()2, passing in the data and the server you want to send the data to. Because UDP is a connectionless protocol, there is no call to connect() beforehand. The last step is to call recvfrom()3 to receive UDP data back. You will also notice that it returns both the data and the details of the remote host and port.

Last updated