Search code examples
ruby-on-railsrubynetwork-programmingnetmask

How to get netmask?


I know how to get from ifconfig. (linux) But is there another way? Can found it in socket.


Solution

  • You need to use IO#ioctl. This is totally non-portable. On my linux box this code words:

    require 'socket'
    sock = Socket.new(Socket::AF_INET, Socket::SOCK_DGRAM,0)
    buf = ["eth0",""].pack('a16h16')
    sock.ioctl(0x891b, buf)
    netmask = "#{buf[20]}.#{buf[21]}.#{buf[22]}.#{buf[23]}" #=> "255.255.255.240"
    

    Ioctl differs considerably between systems and I had to look through a few system header files to get the right sizes for the [].pack, the location of the address in buf and the numeric value for SIOCGIFBRDADDR (the first argument to ioctl).

    If these values don't work for you I can give you more information on how to find them.