#!/usr/bin/python # small server program # which saves input from socket to a file # supports only a single session from one tcp client # can be tested with: telnet # peter.bauer@inode.at import socket, time filename="/var/log/call_log.txt" while 1: # repeat forvever fileh=open(filename,"a") # open file for appending HOST = '' # Symbolic name meaning all available interfaces PORT = 20000 # Arbitrary non-privileged port try: # listen, only for a single session s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: # repeat while data from tcp socket data = conn.recv(1024) # wait for a message to arrive if not data: break # conn.send(data) # send echo back to sender fileh.write(data) # write to file fileh.flush() # flush data to file print data, # only for diagnosis conn.close() # close conn fileh.close() # close filehandle # repeat with file open # catch error: except socket.error: # can happen on socket open if s: # if tcp port is still used from s.close() # previous session print "Could not open socket: " time.sleep(10) # continue listening