Skip to content

Instantly share code, notes, and snippets.

@snapcase snapcase/source_query.rb
Last active Aug 29, 2015

Embed
What would you like to do?
Query Source Servers
#!/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
You can’t perform that action at this time.