Created
October 11, 2010 06:20
-
-
Save manveru/620090 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| require 'ffi' | |
| module SysInfo | |
| extend FFI::Library | |
| ffi_lib [FFI::Library::LIBC] | |
| class IfAddrs < FFI::Struct | |
| layout( | |
| :ifa_next, :pointer, | |
| :ifa_name, :pointer, | |
| :ifa_flags, :uint, | |
| :ifa_addr, :pointer | |
| ) | |
| end | |
| class SockAddrIn < FFI::Struct | |
| layout( | |
| :sin_family, :short, | |
| :sin_port, :ushort, | |
| :sin_addr, :pointer, | |
| :sin_zero, :string | |
| ) | |
| end | |
| attach_function :getloadavg, [:pointer, :int], :int | |
| attach_function :gethostname, [:pointer, :int], :int | |
| attach_function :getifaddrs, [:pointer], :int | |
| attach_function :freeifaddrs, [:pointer], :void | |
| attach_function :getnameinfo, [:pointer, :int, :pointer, :int, :string, :int, :int], :int | |
| module_function | |
| def loadavg | |
| ptr = FFI::MemoryPointer.new(:double, 3) | |
| return unless getloadavg(ptr, 3) == 3 | |
| ptr.get_array_of_double(0, 3) | |
| end | |
| def hostname | |
| name = FFI::MemoryPointer.new(:pointer, 1) | |
| return unless gethostname(name, 1000) == 0 | |
| name.read_string | |
| end | |
| NI_NUMERICHOST = 1 | |
| NI_MAXHOST = 1025 | |
| def ifaddrs | |
| ifap_ptr = FFI::MemoryPointer.new(:pointer) | |
| return unless getifaddrs(ifap_ptr) == 0 | |
| return if ifap_ptr.null? | |
| hash = {} | |
| cur = IfAddrs.new(ifap_ptr.get_pointer(0)) | |
| address_ptr = FFI::MemoryPointer.new(:pointer, NI_MAXHOST) | |
| begin | |
| key = cur[:ifa_name].read_string | |
| tmp = cur[:ifa_addr] | |
| getnameinfo(tmp, SockAddrIn.size, address_ptr, NI_MAXHOST, nil, 0, NI_NUMERICHOST) | |
| hash[key] = address_ptr.read_string | |
| cur = IfAddrs.new(cur[:ifa_next]) | |
| end until cur.pointer.null? | |
| freeifaddrs(ifap_ptr) | |
| hash | |
| end | |
| end | |
| p SysInfo.loadavg | |
| p SysInfo.hostname | |
| p SysInfo.ifaddrs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment