Skip to content

Instantly share code, notes, and snippets.

@tuxfight3r
Forked from kwilczynski/netstat.rb
Created May 25, 2016 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxfight3r/11f7266fbc5c3ab65e3151b9de9b5bdf to your computer and use it in GitHub Desktop.
Save tuxfight3r/11f7266fbc5c3ab65e3151b9de9b5bdf to your computer and use it in GitHub Desktop.
Simple netstat in Ruby
!#/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