How to Listen for Packets on Python

The Python programming language uses the socket library to handle connections to and from remote machines. While the generic socket library will handle the creation of connections, you can use the SocketServer library to create a listening service on one of your computer ports. By setting up a SocketServer object, you can listen for incoming information from outside connections.

Things You'll Need

  • Python Interpreter
Show More

Instructions

    • 1

      Import the socket server libraries into your Python script:
      import SocketServer

    • 2

      Define a class to handle the Server Input:
      class Handler(SocketServer.BaseRequestHandler):

    • 3

      Define a "handle" method in the "Handler" class. This method takes the incoming information and prints it to the screen:
      def handle(self):
      self.data = self.request.recv(1024).strip()
      print "{} wrote:".format(self.client_address[0])
      print self.data

    • 4

      Use the class to run through a SocketServer object, which will stay listening on a certain port indefinitely until terminated:
      server = SocketServer.TCPServer(("localhost", 9999), Handler)
      server.serve_forever()

Related Searches:

References

Comments

Related Ads

Featured