Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ping a specific port and report the results?

I'm making a discord bot for my friends. This one feature, !status, is supposed to ping the server and report the replies.

    from tcping import Ping
    if message.content.startswith('!status'):
        ping = Ping('HOST', 25565)
        response = ping.ping(1)
        await message.channel.send(str(response))

The problem is, the bot only responds with "None." Any help?


1 Answers

Im guessing you want to see if there is something available (as opposed to ping) ... if thats true this might work for you ...

import socket

def check(host,port,timeout=2):
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #presumably 
    sock.settimeout(timeout)
    try:
       sock.connect((host,port))
    except:
       return False
    else:
       sock.close()
       return True

print(check('google.com',1234,timeout=1))
print(check('google.com',443,timeout=1))

maybe you want to time this... easy enough

import time
def timed_check(host,port,timeout=2):
    t0 = time.time()
    if check(host,port,timeout):
       return time.time()-t0 # a bit inexact but close enough

print(timed_check('google.com',1234,timeout=1))
print(timed_check('google.com',443,timeout=1))

or maybe you want stats

def timed_stats_check(host,port,timeout=2,retries=5): 
    minimum,maximum,sumation = float('inf'),float('-inf'),0
    errors = 0
    for i in range(retries):
        t = timed_check(host,port,timeout)
        if t is None:
           print("ERROR Unreachable...")
           errors += 1
        else:
            print(f"Time {t:0.5f}s")
            maximum = max(maximum,t)
            minimum = min(minimum,t)
            sumation += t
    if retries > 0:
        print(f"Max Time: {maximum:0.5f}s")
        print(f"Min Time: {minimum:0.5f}s")
        print(f"Average: {sumation/(retries-errors):0.2f}s")
    print(f"Failures: {errors}/{retries}")
like image 129
Joran Beasley Avatar answered Oct 16 '25 16:10

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!