Python Programming/Sockets

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Previous: Threading Index Next: GUI Programming

[edit] HTTP Client

Make a very simple HTTP client

import socket
s = socket.socket()
s.connect(('localhost', 80))
s.send('GET / HTTP/1.1\nHost:localhost\n\n')
s.recv(40000) # receive 40000 bytes

[edit] NTP/Sockets

Connecting to and reading an NTP time server, returning the time as follows

ntpps       picoseconds portion of time
ntps        seconds portion of time
ntpms       milliseconds portion of time
ntpt        64-bit ntp time, seconds in upper 32-bits, picoseconds in lower 32-bits
import socket
 
BLOCKING = 1            # 0 = non blocking, 1 = blocking
NONBLOCKING = 0         # 0 = non blocking, 1 = blocking
TIME1970            = 2208988800L      # Thanks to F.Lundh
NTPPORT             = 123
MAXLEN              = 1024
NTPSERVER           = ('time.apple.com')
SKTRDRETRYCOUNT         = 2
SKTRDRETRYDLY           = 0.01
 
#***************************************************
## opensocket(servername, port, blocking) \n
# opens a socket at ip address "servername"
# \arg servername = ip address to open a socket to
# \arg port = port number to use
# ntp uses dgram sockets instead of stream
def opensocket(ipaddr, port, mode):
    # create the socket
    skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 
    # open the socket
    try:
        skt.connect((ipaddr, port))
    except socket.error, e:
        print "Failed to connect to server %s %d %d" % (ipaddr, port, mode)
        print "Error %s" % (e.args[0])
        print "Goodbye..."
        sys.exit()
 
    # set the blocking mode (0=nonblocking, 1=blocking)
    try:
        skt.setblocking(mode)
    except socket.error, e:
        print "Failed to set socket blocking mode for %s %d %d" %(ipaddr, port, mode)
        print "Error %s" % (e.args[0])
        print "Goodbye..."
        sys.exit()
 
    return(skt)
 
#***************************************************
##
# we should get 12 long words back in network order \n
# the 10th word is the transmit time (seconds since UT 1900-Jan-01 \n
# I = unsigned long integer \n
# ! = network (big endian) ordering
# \arg \c \b ntpsocket, the socket handle to connect to
# \arg \c \b msg, the message to send to the ntp server
def getntptime(ntpsocket, msg, servername):
    ntpsocket.send(msg)
 
    rtrycnt = 0
    data = 0
    while (data == 0) & (rtrycnt < SKTRDRETRYCOUNT):
        try:
            data = ntpsocket.recv(MAXLEN)
        except socket.error, e:
            rtrycnt += 1
            print "Error reading non-blocking socket, retries = %s, server = %s" %(rtrycnt, servername)
            time.sleep(SKTRDRETRYDLY)       # don't retry too often
 
    # check and see if we got valid data back
    if data:
        ntps = unpack('!12I', data)[10]
        ntpps = unpack('!12I', data)[11]
        if ntps == 0:
            print "Error: NTP, invalid response, goodbye..."
            sys.exit()
    else:
        print "Error: NTP, no data returned, goodbye..."
        sys.exit()
 
    ntpms = ntpps/5000000L                  # 1ms/200ps, we want ms
    ntpt = (ntps << 32) + ntpps
    return (ntpsocket, ntps, ntpps, ntpms, ntpt)
Previous: Threading Index Next: GUI Programming