Browse Source

update regex

New Future 7 years ago
parent
commit
6876b5e6a8
1 changed files with 14 additions and 19 deletions
  1. 14 19
      util/ip.py

+ 14 - 19
util/ip.py

@@ -42,7 +42,6 @@ def local_v4(i=0):  # 本地ipv4地址
     return info[int(i)][-1][0]
     return info[int(i)][-1][0]
 
 
 
 
-
 def public_v4(url="http://v4.ipv6-test.com/api/myip.php"):  # 公网IPV4地址
 def public_v4(url="http://v4.ipv6-test.com/api/myip.php"):  # 公网IPV4地址
     try:
     try:
         return urlopen(url, timeout=60).read()
         return urlopen(url, timeout=60).read()
@@ -59,39 +58,35 @@ def public_v6(url="http://v6.ipv6-test.com/api/myip.php"):  # 公网IPV6地址
             print(e)
             print(e)
 
 
 
 
-def get_ip_config():
+def ip_regex_match(parrent_regex, match_regex):
+    
+    ip_pattern = re.compile(parrent_regex)
+    matcher = re.compile(match_regex)
+    
     if os.name == 'nt':  # windows:
     if os.name == 'nt':  # windows:
         cmd = 'ipconfig'
         cmd = 'ipconfig'
     else:
     else:
-        cmd = 'ifconfig'
-    return os.popen(cmd).readlines()
-
+        cmd = 'ifconfig || ip address'
 
 
-def ip_regex_match(parrent_regex, match_regex):
-    ip_pattern = re.compile(parrent_regex)
-    matcher = re.compile(match_regex)
-    for s in get_ip_config():
+    for s in os.popen(cmd).readlines():
         addr = ip_pattern.search(s)
         addr = ip_pattern.search(s)
+        if addr:
+            print addr.group(1)
         if addr and matcher.match(addr.group(1)):
         if addr and matcher.match(addr.group(1)):
             return addr.group(1)
             return addr.group(1)
 
 
 
 
 def regex_v4(reg): # ipv4 正则提取
 def regex_v4(reg): # ipv4 正则提取
     if os.name == 'nt':  # Windows: IPv4 xxx: 192.168.1.2
     if os.name == 'nt':  # Windows: IPv4 xxx: 192.168.1.2
-        regex_str = r'IPv4 .*: ([\d\.]*)?\W'
-    elif os.uname()[0] == 'Darwin':  # MacOS: inet 127.0.0.1
-        regex_str = r'inet ([\d\.]*)?\s'
-    else:  # LINUX: inet addr:127.0.0.1
-        regex_str = r'inet addr:([\d\.]*)?\s'
+        regex_str = r'IPv4 .*: ((\d{1,3}\.){3}\d{1,3})\W'
+    else:
+        regex_str = r'inet [\w\:]*((\d{1,3}\.){3}\d{1,3})\s'
     return ip_regex_match(regex_str, reg)
     return ip_regex_match(regex_str, reg)
 
 
 
 
 def regex_v6(reg): # ipv6 正则提取
 def regex_v6(reg): # ipv6 正则提取
     if os.name == 'nt':  # Windows: IPv4 xxx: ::1
     if os.name == 'nt':  # Windows: IPv4 xxx: ::1
         regex_str = r'IPv6 .*: ([\:\dabcdef]*)?\W'
         regex_str = r'IPv6 .*: ([\:\dabcdef]*)?\W'
-    elif os.uname()[0] == 'Darwin':  # MacOS: inet ::1
-        regex_str = r'inet6 ([\:\dabcdef]*)?\s'
-    else:  # LINUX: inet6 addr: ::1/128
-        regex_str = r'inet6 addr: ([\:\dabcdef]*)/\d{1,3}\s'
+    else:
+        regex_str = r'inet6 [\w\:]*([\:\dabcdef]*)?\s'
     return ip_regex_match(regex_str, reg)
     return ip_regex_match(regex_str, reg)
-