Skip to content

Instantly share code, notes, and snippets.

@wention
Created March 5, 2018 07:56
Show Gist options
  • Select an option

  • Save wention/9aadc408a90d5c239052a14fea43865d to your computer and use it in GitHub Desktop.

Select an option

Save wention/9aadc408a90d5c239052a14fea43865d to your computer and use it in GitHub Desktop.
class NetUtils:
@classmethod
def CheckInterfaceConnected(cls, inDev):
dev_path = "/sys/class/net/%s" % inDev
carrier_path = dev_path + "/carrier"
opersate_path = dev_path + "/operstate"
retry = 3
carrier = 0
while retry > 0:
try:
fd = open(carrier_path, 'rb')
carrier = fd.read()
break
except IOError as e:
code, msg = e.args
if code == 22: # Invalid argument
ShellPipe('ip', 'link', 'set', 'dev', inDev, 'up').Call()
retry = retry-1
continue
elif code == 2: # No such file or directory
fd = None
raise Exception('NIC interface %s Not Found', inDev)
else:
raise
finally:
if fd:
fd.close()
if int(carrier) == 1:
return True
return False
@classmethod
def GetInterfaceIP(cls, inDev):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment