Skip to content

Instantly share code, notes, and snippets.

@boxofrad
Last active November 3, 2016 11:42
Show Gist options
  • Save boxofrad/28122f430c58cd808e44a197e5bad4af to your computer and use it in GitHub Desktop.
Save boxofrad/28122f430c58cd808e44a197e5bad4af to your computer and use it in GitHub Desktop.
require 'socket'
# Size in bytes of a C `ifreq` structure on a 64-bit system
# http://man7.org/linux/man-pages/man7/netdevice.7.html
#
# struct ifreq {
# char ifr_name[IFNAMSIZ]; /* Interface name */
# union {
# struct sockaddr ifr_addr;
# struct sockaddr ifr_dstaddr;
# struct sockaddr ifr_broadaddr;
# struct sockaddr ifr_netmask;
# struct sockaddr ifr_hwaddr;
# short ifr_flags;
# int ifr_ifindex;
# int ifr_metric;
# int ifr_mtu;
# struct ifmap ifr_map;
# char ifr_slave[IFNAMSIZ];
# char ifr_newname[IFNAMSIZ];
# char *ifr_data;
# };
# };
#
IFREQ_SIZE = 0x0028
# Size in bytes of the `ifr_ifindex` field in the `ifreq` structure
IFINDEX_SIZE = 0x0004
# Operation number to fetch the "index" of the interface
SIOCGIFINDEX = 0x8933
# Open the socket
socket = Socket.open(:PACKET, :RAW)
# Convert the interface name into a string of bytes
# padded with NULL bytes to make it `IFREQ_SIZE` bytes long
ifreq = %w[eth1].pack("a#{IFREQ_SIZE}")
# Perform the syscall
socket.ioctl(SIOCGIFINDEX, ifreq)
# Pull the bytes containing the result out of the string
# (where the `ifr_ifindex` field would be)
index = ifreq[Socket::IFNAMSIZ, IFINDEX_SIZE]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment