Python Socket Client (Network)

Sockets are the basis of any network communication in your computer.  If you open a website, a socket is created in the background. The same thing applies to chat applications or any other network application.

Related Courses

The TCP/IP model
Packets are delivered to another computer using a layered model.  Every layer of the TCP/IP model has a certain purpose. The application layers responsibility is solely the communication language between two applications.  Sockets exist right below the application protocols.

TCP/IP

On the sockets level, you would have to define your own application protocol but you don’t have to worry about network drivers, packet delivery or the internet protocol.

To summarize, sockets work on the application layer.

Python simple socket client
We will create a simple socket client, that mimics a webbrowser. The web uses port 80. The steps a webbrowser does to get a webpage are:

  • create socket
  • get server ip address from domain name
  • connect to server using ip address
  • send request to server
  • receive data (webpage)

In code that will look like:

# Socket client example in python
 
import socket
import sys  

host = 'www.pythonprogramminglanguage.com'
port = 80  # web
 
# create socket
print('# Creating socket')
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print('Failed to create socket')
    sys.exit()
     
 
print('# Getting remote IP address') 
try:
    remote_ip = socket.gethostbyname( host )
except socket.gaierror:
    print('Hostname could not be resolved. Exiting')
    sys.exit()
 
# Connect to remote server
print('# Connecting to server, ' + host + ' (' + remote_ip + ')')
s.connect((remote_ip , port))
 
# Send data to remote server
print('# Sending data to server')
request = "GET / HTTP/1.0\r\n\r\n"
 
try:
    s.sendall(request)
except socket.error:
    print 'Send failed'
    sys.exit()
 
# Receive data
print('# Receive data from server')
reply = s.recv(4096)
 
print reply

Of course all data returned will be shown as the raw html (no images, css etc).

 

Statistics
Socket Server (Network)

One thought on “Python Socket Client (Network)

  1. Reply
    Badcoder - July 1, 2016

    # this line should be like this
    s.sendall(request.encode())

Leave a Reply

Your email address will not be published. Required fields are marked *