Skip to content

Commit 203c215

Browse files
committed
fix(ip): except socket error and using valid IPv6 endpoint
1 parent 28471a3 commit 203c215

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

util/ip.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from re import compile
44
from os import name as os_name, popen
55
from socket import socket, getaddrinfo, gethostname, AF_INET, AF_INET6, SOCK_DGRAM
6-
from logging import debug, error
6+
from logging import debug, warning, error
77
try:
88
# python2
99
from urllib2 import urlopen, Request
@@ -19,19 +19,29 @@
1919

2020

2121
def default_v4(): # 默认连接外网的ipv4
22-
s = socket(AF_INET, SOCK_DGRAM)
23-
s.connect(("1.1.1.1", 53))
24-
ip = s.getsockname()[0]
25-
s.close()
26-
return ip
22+
try:
23+
s = socket(AF_INET, SOCK_DGRAM)
24+
s.connect(("1.1.1.1", 53))
25+
ip = s.getsockname()[0]
26+
s.close()
27+
return ip
28+
except Exception as e:
29+
debug(e)
30+
warning('This device not have IPv4 default route, cannot get valid IPv4 address for DDNS.')
31+
return False
2732

2833

2934
def default_v6(): # 默认连接外网的ipv6
30-
s = socket(AF_INET6, SOCK_DGRAM)
31-
s.connect(('1:1:1:1:1:1:1:1', 8))
32-
ip = s.getsockname()[0]
33-
s.close()
34-
return ip
35+
try:
36+
s = socket(AF_INET6, SOCK_DGRAM)
37+
s.connect(("2606:4700:4700::1111", 53))
38+
ip = s.getsockname()[0]
39+
s.close()
40+
return ip
41+
except Exception as e:
42+
debug(e)
43+
warning('This device not have IPv6 default route, cannot get valid IPv6 address for DDNS.')
44+
return False
3545

3646

3747
def local_v6(i=0): # 本地ipv6地址

0 commit comments

Comments
 (0)