Search code examples
pythonhttp

Listening for HTTP responses


I am trying to write a python application that will listen for HTTP responses on a socket. I am using http-parser for this. Here is my code:

#!/usr/bin/env python
import socket

from http_parser.http import HttpStream
from http_parser.reader import SocketReader

from http_parser.util import b

def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((socket.gethostname(), 7000))
    s.listen(5)
    try:
        while True:
            p = HttpStream(SocketReader(s))
    finally:
        s.close()

if __name__ == "__main__":
    main()

I have two questions:

  1. Is this the best way to do this? Note that I do not want to send a request and then listen for a response. I want to have a redirection mechanism that redirects all responses to the box running this script.
  2. How should I test this? Is there a tool that can mock HTTP responses?

EDIT What I am trying to do is this: I have three boxes, once runs Apache, one runs this script and one is the client. When the client connects to Apache and it sends back a response, I am diverting the response to this box. So in this script, I am trying to listen for HTTP responses.

Topology Here is my topology: Server <----> Switch one <-----> Switch two <-----> Box one and two Initially, box one connects to the server and sends a request. When the second switch receives responses from the server, it forks it to both box one and box two.


Solution

  • I ended up using a raw socket and directly reading packets from it.