Created
March 5, 2018 07:56
-
-
Save wention/9aadc408a90d5c239052a14fea43865d 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
| 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