class PosixPsutil::Network

Public Class Methods

net_connections(interface=:inet) click to toggle source

interface can be one of [:inet, :inet4, inet6, :udp, :udp4, :udp6, :tcp, :tcp4, :tcp6, :all, :unix]

the default interface is :inet, contains udp and tcp return #<OpenStruct inode, laddr, raddr, family, type, status, fd, pid>

# File linux/system.rb, line 450
def self.net_connections(interface=:inet)
  ret = []
  connection = Connection.new
  return nil unless connection.tmap.key?(interface)
  inodes = Processes.get_all_inodes
  connection.tmap[interface].each do |kind|
    f, family, type = kind
    if [AF_INET, AF_INET6].include?(family)
      ret.concat(connection.process_inet("/proc/net/#{f}", family, 
                                         type, inodes))
    else
      ret.concat(connection.process_unix("/proc/net/#{f}", family, inodes))
    end
  end
  ret
end
net_io_counters(pernic=false) click to toggle source

Get counters of network io (per network interface)

When pernic is true, return a hash contains network io of each interface, otherwise return sum of all interfaces.

The network io of each/all interface(s) is represented in #<OpenStruct bytes_recv, packets_recv, errin, dropin, bytes_sent, packets_sent, errout, dropout>.

# File linux/system.rb, line 405
def self.net_io_counters(pernic=false)
  lines = IO.readlines('/proc/net/dev')[2..-1]
  if pernic
    ret = {}
    lines.each do |line|
      colon = line.rindex(':')
      name = line[0...colon].strip()
      fields = line[(colon + 1)..-1].strip.split(' ')
      counter = OpenStruct.new
      counter.bytes_recv = fields[0].to_i
      counter.packets_recv = fields[1].to_i
      counter.errin = fields[2].to_i
      counter.dropin = fields[3].to_i
      counter.bytes_sent = fields[8].to_i
      counter.packets_sent = fields[9].to_i
      counter.errout = fields[10].to_i
      counter.dropout = fields[11].to_i
      ret[name.to_sym] = counter
    end
    return ret
  else
    counter = OpenStruct.new(bytes_recv: 0, packets_recv: 0, 
                             errin: 0, dropin: 0, bytes_sent: 0, 
                             packets_sent: 0, errout: 0, dropout: 0)
    lines.each do |line|
      colon = line.rindex(':')
      fields = line[(colon + 1)..-1].strip.split(' ')
      counter.bytes_recv += fields[0].to_i
      counter.packets_recv += fields[1].to_i
      counter.errin += fields[2].to_i
      counter.dropin += fields[3].to_i
      counter.bytes_sent += fields[8].to_i
      counter.packets_sent += fields[9].to_i
      counter.errout += fields[10].to_i
      counter.dropout += fields[11].to_i
    end
    return counter
  end
end