Home > Mobile >  python script to calc internet upload and download and jitter
python script to calc internet upload and download and jitter

Time:12-08

I have a Python script that runs by ping to determine the internet speed every 30 seconds, to see if a user can receive a call over the internet, ping is often not enough to know this so I want more information like download speed and network upload speed and so on.

How can this happen in Python without having a significant impact on the Internet so that it does not cause a slow internet

`
def check_ping(host):
    """
    Returns formated min / avg / max / mdev if there is a vaild host
    Return None if host is not vaild
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower() == 'windows' else '-c'

    # Building the command. Ex: "ping -c 1 $host"
    command = ['ping', param, '3', host]

    # ask system to make ping and return output
    ping = subprocess.Popen(command, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    out, error = ping.communicate()
    matcher = re.compile(
        "(\d .\d )/(\d .\d )/(\d .\d )/(\d .\d )")
    # rtt min/avg/max/mdev =
    ping_list = r"Minimum = (\d )ms, Maximum = (\d )ms, Average = (\d )ms"

    try:
        if(not error):
            if(platform.system().lower() == 'windows'):
                response = re.findall(ping_list, out.decode())[0]
                return response
            else:
                response = matcher.search(out.decode()).group().split('/')
                return response
    except Exception as e:
        logging.error(e)
        return None

`

CodePudding user response:

pyspeedtest provides you with features you want.

Here is a snippet from the official page.

>>> import pyspeedtest
>>> st = pyspeedtest.SpeedTest()
>>> st.ping()
9.306252002716064
>>> st.download()
42762976.92544772
>>> st.upload()
19425388.307319913

There is also speedtest-cli but this is not something that I've personally tried.

If you're looking for something more, then you have to come up with your own implementation based on sockets

EDIT: Here is an implementation based on using requests

#!/usr/bin/env python3
import requests, os, sys, time

def test_connection(type):
  nullFile = os.devnull
  with open(nullFile, "wb") as f:
    start = time.clock()
    if type == 'download':
       r = requests.get('https://httpbin.org/get', stream=True)
    elif type == 'upload':
       r = requests.post('https://httpbin.org/post', data={'key': 'value'})
    else:
       print("unknown operation")
       raise

    total_length = r.headers.get('content-length')
    dl = 0

    for chunk in r.iter_content(1024):
        dl  = len(chunk)
        f.write(chunk)
        done = int(30 * dl / int(total_length))
        sys.stdout.write("\r%s: [%s%s] %s Mbps" % (type, '=' * done, ' ' * (30-done), dl//(time.clock() - start) / 100000))
        print('')

# Example usage
test_connection("download")
test_connection("upload")

Output:

download: [==============================] 0.13171 Mbps
upload: [==============================] 0.20217 Mbps

You can probably modify this function to accept url/IP as an argument. Also, you can find more details on requests module on the official page

  • Related