How to find out if server is closing connection in python requests module

I am using python requests module to generate traffic on my web server,

After a connection with a specific request should break and I want to trigger a callback if the connection is closed (maybe the server is sending a FIN or RESET flag).

How can I find the server or close the connection in the Requests module, I don't want to use tcpdump or any packet capture utility to verify this.

 82     def request_per_session(self, request, method='post', page=None,**options):
 83         url=self.url
 84         if page:url+=page
 85         print pprint.pprint(options)
 86         s = requests.Session()
 87         httpmethodToCall = getattr(s, method)
 88         print pprint.pprint(httpmethodToCall)
 89         for n in range(request):
 90             print "running %d" %n
 91             if method == 'get':
 92                 r=httpmethodToCall(url)
 93             else:
 94                 r=httpmethodToCall(url,options)
 95             print r.status_code

      

+3


source to share


1 answer


This can be done more efficiently with a port scanner.

To develop, I am assuming that you are sending / receiving data on port 80. With this information, just create a socket, try to connect to the given host, and if there is an error, you can either discard the exception or print it. For example:

import socket

def checkServer(server):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        socket.connect((socket.gethostbyname(server), 80))
        return None
    except socket.error as e:
        return e

      



In this code, if there is no error, then nothing is returned (in the form None

), but if there is an error, the exception object is passed back. The code is much cleaner than using a module Requests

because it deals with low level connections, which is great if you want to check if any things are open, data transfers, etc., but they are terrible for sending data, cleaning up the web pages, etc. Something like urllib2

or Requests

would be better for this.

Hope this helps.

0


source







All Articles