Learning Python Network Programming

(Sean Pound) #1

Programming with Sockets


Let's try to connect a client socket to a server process. The following code is an
example of TCP client socket that makes a connection to server socket:


import socket
import sys

if __name__ == '__main__':

try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
print("Failed to crate a socket")
print("Reason: %s" %str(err))
sys.exit();

print('Socket created')

target_host = input("Enter the target host name to connect: ")
target_port = input("Enter the target port: ")

try:
sock.connect((target_host, int(target_port)))
print("Socket Connected to %s on port: %s" %(target_host,
target_port))
sock.shutdown(2)
except socket.error as err:
print("Failed to connect to %s on port %s" %(target_host,
target_port))
print("Reason: %s" %str(err))
sys.exit();

If you run the preceding TCP client, an output similar to the following will be shown:


python 7_1_tcp_client_socket.py


Socket created


Enter the target host name to connect: 'www.python.org'


Enter the target port: 80


Socket Connected to http://www.python.org on port: 80


However, if socket creation has failed for some reason, such as invalid DNS,
an output similar to the following will be shown:


python 7_1_tcp_client_socket.py


Socket created

Free download pdf