handle socket.error
This commit is contained in:
parent
f05a35dd96
commit
fd7253ded7
1 changed files with 25 additions and 22 deletions
|
@ -61,34 +61,37 @@ pack_port = lambda i: struct.pack('>H', i)
|
||||||
|
|
||||||
def mcping_modern(host, port):
|
def mcping_modern(host, port):
|
||||||
""" pings a server using the modern (1.7+) protocol and returns data """
|
""" pings a server using the modern (1.7+) protocol and returns data """
|
||||||
# connect to the server
|
|
||||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
s.connect((host, port))
|
# connect to the server
|
||||||
except socket.gaierror:
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
raise PingError("Invalid hostname")
|
|
||||||
except socket.timeout:
|
|
||||||
raise PingError("Request timed out")
|
|
||||||
|
|
||||||
# send handshake + status request
|
try:
|
||||||
s.send(pack_data("\x00\x00" + pack_data(host.encode('utf8')) + pack_port(port) + "\x01"))
|
s.connect((host, port))
|
||||||
s.send(pack_data("\x00"))
|
except socket.gaierror:
|
||||||
|
raise PingError("Invalid hostname")
|
||||||
|
except socket.timeout:
|
||||||
|
raise PingError("Request timed out")
|
||||||
|
|
||||||
# read response
|
# send handshake + status request
|
||||||
unpack_varint(s) # Packet length
|
s.send(pack_data("\x00\x00" + pack_data(host.encode('utf8')) + pack_port(port) + "\x01"))
|
||||||
unpack_varint(s) # Packet ID
|
s.send(pack_data("\x00"))
|
||||||
l = unpack_varint(s) # String length
|
|
||||||
|
|
||||||
if not l > 1:
|
# read response
|
||||||
raise PingError("Invalid response")
|
unpack_varint(s) # Packet length
|
||||||
|
unpack_varint(s) # Packet ID
|
||||||
|
l = unpack_varint(s) # String length
|
||||||
|
|
||||||
d = ""
|
if not l > 1:
|
||||||
while len(d) < l:
|
raise PingError("Invalid response")
|
||||||
d += s.recv(1024)
|
|
||||||
|
|
||||||
# Close our socket
|
d = ""
|
||||||
s.close()
|
while len(d) < l:
|
||||||
|
d += s.recv(1024)
|
||||||
|
|
||||||
|
# Close our socket
|
||||||
|
s.close()
|
||||||
|
except socket.error:
|
||||||
|
raise PingError("Socket Error")
|
||||||
|
|
||||||
# Load json and return
|
# Load json and return
|
||||||
data = json.loads(d.decode('utf8'))
|
data = json.loads(d.decode('utf8'))
|
||||||
|
|
Reference in a new issue