minetestbot-modules/serverup.py

77 lines
2.0 KiB
Python
Raw Normal View History

2018-11-05 08:49:02 -08:00
#!/usr/bin/env python3
2013-01-07 10:00:44 -08:00
"""
serverup.py - Minetest server ping module
2018-11-05 08:49:02 -08:00
Copyright 2018, sfan5
Licensed under GNU General Public License v2.0
2013-01-07 10:00:44 -08:00
"""
2018-11-05 08:49:02 -08:00
import socket
import time
2013-01-07 10:00:44 -08:00
def check(host, port):
try:
ai = socket.getaddrinfo(host, port, proto=socket.IPPROTO_UDP)[0]
except socket.gaierror:
return None, "host did not resolve"
if all(c in "0123456789." for c in host) or ":" in host:
ipproto = "" # is obvious to the user
else:
ipproto = "IPv6" if ai[0] == socket.AF_INET6 else "IPv4"
sock = socket.socket(*ai[:3])
2018-11-05 08:49:02 -08:00
sock.settimeout(2.0)
sock.connect(ai[4])
2018-11-05 08:49:02 -08:00
try:
# ask for a peer id
sock.send(b"\x4f\x45\x74\x03\x00\x00\x00\x01")
2018-11-05 08:49:02 -08:00
start = time.time()
data = sock.recv(1024)
if not data:
return None, ipproto
2018-11-05 08:49:02 -08:00
end = time.time()
# disconnect again
2018-11-05 08:49:02 -08:00
peer_id = data[12:14]
sock.send(b"\x4f\x45\x74\x03" + peer_id + b"\x00\x00\x03")
return end - start, ipproto
except socket.error:
return None, ipproto
finally:
2018-11-05 08:49:02 -08:00
sock.close()
2013-01-07 10:00:44 -08:00
def serverup(phenny, input):
2021-01-24 03:24:52 -08:00
arg = input.group(2).strip()
2013-01-07 10:00:44 -08:00
if not arg:
return phenny.reply("give me an address and (optionally) a port")
2018-11-05 08:49:02 -08:00
if '.' in arg: # IPv4 or a domain name
arg = arg.replace(":", " ")
if ' ' in arg:
2018-11-05 08:49:02 -08:00
address, port = arg.split(' ')
try:
port = int(port)
except ValueError:
return phenny.reply("invalid port")
2013-01-07 10:00:44 -08:00
else:
address = arg
2018-11-05 08:49:02 -08:00
port = 30000
if port < 1024 and port >= 2**16:
return phenny.reply("invalid port")
if ":" in address:
desc = "[%s]:%d" % (address, port)
else:
desc = "%s:%d" % (address, port)
result, extra = check(address, port)
2018-11-05 08:49:02 -08:00
if result is None:
msg = "%s seems to be down" % desc
2018-11-05 08:49:02 -08:00
else:
msg = "%s is up (%dms)" % (desc, result*1000)
if extra != "":
msg += " (%s)" % extra
phenny.say(msg)
2013-01-07 10:00:44 -08:00
serverup.commands = ['up']
if __name__ == '__main__':
2014-07-20 07:13:59 -07:00
print(__doc__)