Last active
August 29, 2015 14:22
-
-
Save snapcase/8cbede0ffd7e993c5a9e to your computer and use it in GitHub Desktop.
Query Source Servers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'socket' | |
class SourceQuery | |
def initialize(ip, port) | |
query(ip, port) | |
end | |
def to_s | |
"%s | %s | %d/%d" % [@name, @map, @players, @max_players] | |
end | |
private | |
def query(ip, port) | |
sock = UDPSocket.new | |
data = [-1, -1, 'T', 'Source Engine Query'].pack('s2aa*x') | |
sock.send(data, 0, ip, port) | |
ready = IO.select([sock], nil, nil, 5) | |
if ready | |
parse(sock.recvfrom(1024)) | |
else | |
raise "server not responding" | |
end | |
ensure | |
sock.close | |
end | |
def parse(data) | |
unpacked = data[0].unpack('@6Z*Z*Z*Z*s!CCCaaCC') | |
keys = [:name, :map, :folder, :game, :id, | |
:players, :max_players, :bots, | |
:server_type, :environment, | |
:visibility, :vac] | |
info = keys.zip(unpacked).to_h | |
info.each do |key, value| | |
self.class.send(:attr_reader, key) | |
instance_variable_set("@#{key}", value) | |
end | |
end | |
end | |
def run! | |
server = SourceQuery.new(*ARGV.first.split(":")) | |
puts server | |
end | |
run! if __FILE__ == $0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment