Python Networking Basics

  • When you use your web browser, you usually type some address, like the one in your URL bar, now.

  • That URL isn’t the real address. It is a name that corresponds to the real address.

$ nslookup gnomon.securitystandard.org
Server:             10.168.123.11
Address:    10.168.123.11#53
Non-authoritative answer:
gnomon.securitystandard.org canonical name = hermes.securitystandard.org.
Name:       hermes.securitystandard.org
Address: 185.172.165.184
  • The real address of gnomon is 185.172.165.184 !

  • So, what are those numbers? We’re back to binary fun!

IP Addresses

  • Each of these numbers separated by dots is called an “octet.”

  • Here is how they look in binary. Let’s do the math and prove it.

185

172

165

184

10111001

10101100

10100101

10111000

  • Quiz yourself: What is the biggest number that fits in an octet?

Talking between computers

  • To listen for a connection on your computer from another computer, you must hold socket.

  • A socket is an IP address and a port number. To see which ports are in use on your computer, try this command:

netstat -an
  • Lets write a program to talk between computers.

Talk server
 1#!/bin/env python
 2import socket
 3# We establish a variable called server that opens a socket.
 4server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 5# We will listen on port 9087 on 0.0.0.0, which means *every IP*
 6# Notice that we pass something in parentheses
 7listentuple = ('0.0.0.0', 9087)
 8server.bind(listentuple) # Own the IP and port!
 9server.listen(50) # Start listening
10print("Starting server.")
11data = ''
12
13while True:
14    conn, addr = server.accept() # See who is talking to us
15    print('Connected with ' + addr[0] + ':' + str(addr[1]))
16    while "bye" not in data:
17        data = conn.recv(1024)
18        conn.sendall('You said ' + data + '\n')
19        print("I got " + data)
20    print("Stopping server.")
21    server.shutdown(0)
22    server.close()
23    break
Talk client
 1import socket
 2def netcat(hostname, port, content):
 3    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 4    s.connect((hostname, port))
 5    s.sendall(content)
 6    s.shutdown(socket.SHUT_WR)
 7    while 1:
 8        data = s.recv(1024)
 9        if data == "":
10            break
11        print("Received:", repr(data))
12    print("Connection closed.")
13    s.close()
14# Use...
15#   sendtohost('xxx.xxx.xxx.xxx', portnumber, "What I wanted to say.")

Downloading Things from the Internet

A function that checks if we fed Python an IP and a port to make a socket
 1import socket
 2def isipandport(socketstring):
 3    '''Tests for an ipv4 address and a realistic port number'''
 4    # If socketstring is empty, it is false, so we return False and quit.
 5    if not socketstring:
 6        return(False)
 7    # Let us make sure it contains a string or we transform it into one.
 8    socketstring = str(socketstring)
 9    # We will try to use it as an address.
10    try:
11        ip, port = socketstring.split(':')
12        socket.inet_aton(ip)
13        port = int(port)
14    # If we fail, we will complain.
15    except:
16        print('malformed socket in ' + socketstring)
17        return(False)
18    # If the port number is less than 7 or greater than the maximum integer,
19    #  We will whine about it, but accept it.
20    if (port < 7) or (port > 65535):
21        print('port out of range in ' + socketstring)
22    return(True)
a set of commands to copy the web page for the Python programming language.
1import urllib.request
2f = urllib.request.urlopen('http://www.python.org/')
3v1 = f.read()
4FH = open('c:/temp/mycopy.html', 'w')
5FH.write(v1)
6FH.close()
  • Now, try this:

    • Ask the user for an IP and port number. If the user gives you one, say ‘Thanks!’ If not, say ‘Wrong!’

    • Download the Python web page and display your local copy in a web browser by opening the URL file:///c:/temp/mycopy.html .