Search code examples
pythonpython-3.xproxylatency

How to easily obtain the latency of proxies with only a few lines of code in python?


I am making something in one of my scripts that should be able to weed out all of my proxies that are slow. The proxies are stored on each line a file called proxies.txt. I want to be able to specify the maximum latency in milliseconds with a variable. I saw a similar question here Python requests find proxy latency but it was unanswered. If there is a way to do this please let me know.


Solution

  • This wasn't 100% of what you asked for this returns a true or false depending on if the proxy responds in time

    def ping(host):
    
        param = '-n' if platform.system().lower() == 'windows' else '-c'
    
        command = ['ping', param, '1', '-w', 250, '-n', '1', host]
        return subprocess.call(command, stdout=subprocess.PIPE) == 0
    

    That returns a boolean (true or false) if it responds within 250 milliseconds. I'm sure it it easy enough to modify this to return that to return the correct value. Then all you would need to do is put that in a for loop for each line in the file. also with this you would have to strip the port number and semicolon off of the proxy test it then re-attach it which I did in this code: You will have to change this if you want to use this because this is from a project I coded.

    def check_proxies(filename):
        filename = str(filename)
        f = open(filename)
        lines = 0
        for _ in f:
            lines = lines + 1
        f.close()
    
        EstimatedTime = lines * config.Ping_Timeout
        print(f"{bcolors.Blue}Checking proxies... this will take at max {bcolors.OKGREEN}{EstimatedTime / 1000}{bcolors.Blue} seconds{bcolors.ENDC}")
    
        with open(filename) as f:
            workingProxies = []
            LineNum = 0
            for line in f.readlines():
                line = line.strip("\n").strip('\r')
                line = line.split(":")
                line_port = line[1]
                line_ip = line[0]
                if LineNum == 50:
                    if config.extras.Proxy_Joke.Proxy_Joke_Extra:
                        Info.print_dad_joke()
                    else:
                        pass
                LineNum = LineNum + 1
                if ping(line_ip):
                    workingProxies = workingProxies + [f"{line_ip}:{line_port}"]
                else:
                    pass
            if len(workingProxies) == 0:
                print("Error, no working proxies were detected, are you connected to the internet?")
        return workingProxies
    
    
    def get_file_lines():
        InputProxies = 0
        with open(config.Proxy_File) as G:
            for _ in G.readlines():
                InputProxies = InputProxies + 1
        return InputProxies
    

    I don't know how I'd go about doing what you want to do but this worked for me in a project I worked on.