Python Quick Notes :: Part - 5


Bhaskar S 03/16/2013

Hands-on With Python - V

Python provides excellent support for network programming using the socket class from the Python module socket. The following are some of the frequently used functions from socket class:

The following is the python program named sample-23.py:

sample-23.py
#
# Name: sample-23.py
#

# ----- Python networking -----

import socket

# Get the host name of the machine

host = socket.gethostname()

print("Machine host name: %s" % (host))

# Get the host IP address

ip = socket.gethostbyname(host)

print("Machine's IP address: %s" % (ip))

gip = socket.gethostbyname("www.google.com")

print("www.google.com's IP address: %s" % (gip))

# Get primary host name, aliases, and ip address list

(host, aliases, ipaddrs) = socket.gethostbyaddr(ip)

print("Aliases: ", aliases)
print("IP address(es): ", ipaddrs)

Execute the following command:

python sample-23.py

The following is the output:

Output (sample-23.py)

Machine host name: nutcracker
Machine IP address: 127.0.1.1
www.google.com's IP address: 173.194.75.103
Aliases:  []
IP address(es):  ['127.0.1.1']
Aliases:  []
IP address(es):  ['173.194.75.103']

We will now test a simple TCP server and client. First start the server and then the client.

The following is the simple python TCP server program named sample-24.py:

sample-24.py
#
# Name: sample-24.py
#

# ----- Python networking - Simple TCP server -----

import socket

# Create a TCP socket object instance

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("---> Created TCP server socket .....")

# Assign the server host and port

address = ('localhost', 9090)

# Bind the server socket to the address

try:
    server.bind(address)
except Exception as e:
    print(e)
    exit(1)

print("---> Bound to address ", address)

# Listen for incoming connections

server.listen(5)

print("---> TCP Server socket ready and listening .....")

size = 1024

while True:
    # Accept incoming client connection

    client, caddr = server.accept()

    print("---> TCP Client connection from address: ", caddr)

    # Receive client data

    data = client.recv(size)

    print("---> Received data from client %s: %s" % (caddr, data))

    # Send data back to client

    sent = client.send("TCP Server Replay: " + data)

    print("---> Sent %d bytes of data to client %s" % (sent, caddr))

    # Close client connection

    client.close()

Execute the following command:

python sample-24.py

The following is the output:

Output (sample-24.py)

---> Created TCP server socket .....
---> Bound to address  ('localhost', 9090)
---> TCP Server socket ready and listening .....

The following is the simple python TCP client program named sample-25.py:

sample-25.py
#
# Name: sample-25.py
#

# ----- Python networking - Simple TCP client -----

import socket

# Create a TCP socket object instance

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("---> Created TCP client socket .....")

# Assign the server host and port

address = ('localhost', 9090)

# Connect to the server at the address

try:
    client.connect(address)
except Exception as e:
    print(e)
    exit(1)

print("---> Connected to TCP server at address ", address)

data = "Hello Python"

size = 1024

# Send data to the server

sent = client.send(data)

print("---> Sent %d bytes of data to the server %s" % (sent, address))

# Receive response data from the server

data = client.recv(size)

print("---> Received data from server %s: %s" % (address, data))

# Close connection to server

client.close()

Execute the following command:

python sample-25.py

The following is the output:

Output (sample-25.py)

---> Created TCP client socket .....
---> Connected to TCP server at address  ('localhost', 9090)
---> Sent 12 bytes of data to the server ('localhost', 9090)
---> Received data from server ('localhost', 9090): TCP Server Replay: Hello Python

Next, we will now test a simple UDP server and client. First start the server and then the client.

The following is the simple python UDP server program named sample-26.py:

sample-26.py
#
# Name: sample-26.py
#

# ----- Python networking - Simple UDP server -----

import socket

# Create a socket object instance

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print("---> Created UDP server socket .....")

# Assign the server host and port

address = ('localhost', 9091)

# Bind the server socket to the address

try:
    server.bind(address)
except Exception as e:
    print(e)
    exit(1)

print("---> Bound to address ", address)

size = 1024

while True:
    # Receive client data

    data, caddr = server.recvfrom(size)

    print("---> Received data from client %s: %s" % (caddr, data))

    # Send data back to client

    sent = server.sendto("UDP Server Replay: " + data, caddr)

Execute the following command:

python sample-26.py

The following is the output:

Output (sample-26.py)

---> Created UDP server socket .....
---> Bound to address  ('localhost', 9091)

The following is the simple python UDP client program named sample-27.py:

sample-27.py
#
# Name: sample-27.py
#

# ----- Python networking - Simple UDP client -----

import socket

# Create a UDP socket object instance

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print("---> Created UDP client socket .....")

# Assign the server host and port

address = ('localhost', 9091)

data = "Hello Python"

size = 1024

# Send data to the server

sent = client.sendto(data, address)

print("---> Sent %d bytes of data to the server %s" % (sent, address))

# Receive response data from the server

data, saddr = client.recvfrom(size)

print("---> Received data from server %s: %s" % (saddr, data))

# Close client socket

client.close()

Execute the following command:

python sample-27.py

The following is the output:

Output (sample-27.py)

---> Created UDP client socket .....
---> Sent 12 bytes of data to the server ('localhost', 9091)
---> Received data from server ('127.0.0.1', 9091): UDP Server Replay: Hello Python

Python provides support for accessing web resources using the Python module urllib.

The following is the python program named sample-28.py:

sample-28.py
#
# Name: sample-28.py
#

# ----- Python URL library for Web access -----

import urllib.request, urllib.parse, urllib.error

response = urllib.request.urlopen('http://www.google.com/')

url = response.geturl()

print("URL: ", url)
print("")

data = response.read()

print("Response data length: ", len(data))
print("")

headers = response.info()

print("HTTP Response Headers:")
print("----------------------")
print("")

print(headers)

Execute the following command:

python sample-28.py

The following is the output:

Output (sample-28.py)

URL:  http://www.google.com/

Response data length:  10846

HTTP Response Headers:
----------------------

Date: Sun, 17 Mar 2013 18:44:40 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=e675c66ab3053b32:FF=0:TM=1363545880:LM=1363545880:S=jcSLoyehfQDvCTRM; expires=Tue, 17-Mar-2015 18:44:40 GMT; path=/; domain=.google.com
Set-Cookie: NID=67=o41thIplYdRdA-K4zczsDt3P4PzvTZkFrOW94MtKbVHWShlfwWmsjfNigJ7YnleQpFuTDtgx3s_FHCzzI4_opSy_1yGcm8eyQpsf7Mg_uVsXamS-XKUZhc7NuFnb5AYk; expires=Mon, 16-Sep-2013 18:44:40 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

References

Python Quick Notes :: Part - 1

Python Quick Notes :: Part - 2

Python Quick Notes :: Part - 3

Python Quick Notes :: Part - 4