Skip to content

Instantly share code, notes, and snippets.

@hisui
Last active December 20, 2015 13:29
Show Gist options
  • Save hisui/6138942 to your computer and use it in GitHub Desktop.
Save hisui/6138942 to your computer and use it in GitHub Desktop.
Counting number of TCP/IP connections established between given two processes.
#!/usr/local/bin/ruby
require "pp"
if ARGV.size < 2
$stderr.puts "Usage: ruby ipip.rb PID1 PID2"
exit -1
end
pid_1 = ARGV[0]
pid_2 = ARGV[1]
LsofRecord = Struct.new :command, :pid, :user, :fd, :type, :device, :size, :node, :name, :state
def lsof_by_pid(pid)
`lsof -P -p #{pid}`.lines.map {|e| LsofRecord.new(* e.split(/\s+/)) }
end
def lsof_tcp_arrow(a)
a.select(&:name).map {|e| e.name.split(/->/) }.select {|e| e.size == 2 }
end
backet = {}
count = 0
lsof_tcp_arrow(lsof_by_pid(pid_1)).each {|e| backet[e] = 1 }
lsof_tcp_arrow(lsof_by_pid(pid_2)).each {|e|
count += 1 if backet[e.reverse]
}
puts count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment