Skip to content

Instantly share code, notes, and snippets.

@trhura
Last active April 5, 2019 12:51
Show Gist options
  • Save trhura/5811896 to your computer and use it in GitHub Desktop.
Save trhura/5811896 to your computer and use it in GitHub Desktop.
if_nametoindex, if_indextoname functions for python 2.x. In python 3.x, they are available in socket module.
import ctypes
import ctypes.util
libc = ctypes.CDLL(ctypes.util.find_library('c'))
def if_nametoindex (name):
if not isinstance (name, str):
raise TypeError ('name must be a string.')
ret = libc.if_nametoindex (name)
if not ret:
raise RunTimeError ("Invalid Name")
return ret
def if_indextoname (index):
if not isinstance (index, int):
raise TypeError ('index must be an int.')
libc.if_indextoname.argtypes = [ctypes.c_uint32, ctypes.c_char_p]
libc.if_indextoname.restype = ctypes.c_char_p
ifname = ctypes.create_string_buffer (32)
ifname = libc.if_indextoname (index, ifname)
if not ifname:
raise RuntimeError ("Inavlid Index")
return ifname
@thielemans
Copy link

thielemans commented Apr 5, 2019

Exactly what I needed. Thanks! This is now included in socket since Python 3.3 but is not available in 2.7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment