1

I am trying to write a Python program that listens in the background (as a daemon) on a defined port and IP and then validate incoming data (fixed CSV format output from a PBX), in that it verifies the source IP, and performs a check against the date field (if year == 1899 then set a missed call indicator in the insert) If valid, inserts record into a PostgreSQL database, otherwise log to syslog with an error. I figured I should use socket to listen to the specific port and IP?

import socket

IP = 192.168.1.1               # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((IP, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

Am I doing everything right? How do I validate IP and perform the required tasks? Thanks

New Folder
  • 97
  • 1
  • 2
  • 14
  • Check the docs for socket.socket for reading IP of the other end; add some processing to 'data' before sending it back to the socket. -- [getpeername at http://docs.python.org/library/socket.html ] – greggo Oct 12 '12 at 04:00
  • have you considered using http protocol instead? There are many tools that make it easier to implement, more reliable, easier to test and maintain – jfs Oct 12 '12 at 04:02
  • Where is your specific issue? The sample you have above looks like a simple echo server- does it not work? Are you questioning how to use syslog or Postgres? What do you mean by 'validate IP'? Are you wanting to limit connections to be from only specific addresses? – tMC Oct 12 '12 at 04:09
  • Yes the connection has to be only from the specific address. Yes, I want to limit connection to be from only the specific address. – New Folder Oct 12 '12 at 04:15
  • 1
    s.accept() returns a tuple of (client_socket, (IP, PORT)), which contains the client's IP of course, is that what you're looking for? – andrean Oct 12 '12 at 04:46
  • I think SimpleXMLRPCServer could be the better idea. Can we listen to the specifc IP and port using SimpleXMLRPCServer? – New Folder Oct 12 '12 at 05:52
  • To extend my previous comment: sockets might be too low level that are [hard to get right even for simple things](http://stackoverflow.com/questions/12730477/close-is-not-closing-socket-properly). You could start at a higher level (web-application) where all gory details are hidden. See [flask tutorial](http://maximebf.com/blog/2012/10/building-websites-in-python-with-flask/). – jfs Oct 12 '12 at 13:31

0 Answers0