-
-
Save tuxfight3r/11f7266fbc5c3ab65e3151b9de9b5bdf to your computer and use it in GitHub Desktop.
Simple netstat in Ruby
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/env ruby | |
PROC_NET_TCP = '/proc/net/tcp' # This should always be the same ... | |
TCP_STATES = { '00' => 'UNKNOWN', # Bad state ... Impossible to achieve ... | |
'FF' => 'UNKNOWN', # Bad state ... Impossible to achieve ... | |
'01' => 'ESTABLISHED', | |
'02' => 'SYN_SENT', | |
'03' => 'SYN_RECV', | |
'04' => 'FIN_WAIT1', | |
'05' => 'FIN_WAIT2', | |
'06' => 'TIME_WAIT', | |
'07' => 'CLOSE', | |
'08' => 'CLOSE_WAIT', | |
'09' => 'LAST_ACK', | |
'0A' => 'LISTEN', | |
'0B' => 'CLOSING' } # Not a valid state ... | |
if $0 == __FILE__ | |
STDOUT.sync = true | |
STDERR.sync = true | |
File.open(PROC_NET_TCP).each do |i| | |
i = i.strip | |
next unless i.match(/^\d+/) | |
i = i.split(' ') | |
local, remote, state = i.values_at(1, 2, 3) | |
local_IP, local_port = local.split(':').collect { |i| i.to_i(16) } | |
remote_IP, remote_port = remote.split(':').collect { |i| i.to_i(16) } | |
connection_state = TCP_STATES.fetch(state) | |
local_IP = [local_IP].pack('N').unpack('C4').reverse.join('.') | |
remote_IP = [remote_IP].pack('N').unpack('C4').reverse.join('.') | |
puts "#{local_IP}:#{local_port} " + | |
"#{remote_IP}:#{remote_port} #{connection_state}" | |
end | |
exit(0) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment