feat: get local ip from socket
This commit is contained in:
parent
ca46f0d9d8
commit
4020213ff4
@ -370,8 +370,17 @@ async def receive_request(i_m: IP_Message):
|
|||||||
|
|
||||||
|
|
||||||
def get_own_ip() -> str:
|
def get_own_ip() -> str:
|
||||||
ip = os.environ.get("HOST_IP", "IP not set")
|
ip = os.environ.get("HOST_IP")
|
||||||
return ip
|
if not ip: # 如果环境变量中没有IP
|
||||||
|
try:
|
||||||
|
# 从网卡获取IP
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
s.connect(("8.8.8.8", 80)) # 通过连接Google DNS获取IP
|
||||||
|
ip = s.getsockname()[0]
|
||||||
|
s.close()
|
||||||
|
except:
|
||||||
|
raise ValueError("Unable to get IP")
|
||||||
|
return str(ip)
|
||||||
|
|
||||||
|
|
||||||
# get node list from central server
|
# get node list from central server
|
||||||
|
12
src/node.py
12
src/node.py
@ -42,7 +42,17 @@ def send_ip():
|
|||||||
# 用环境变量获取本机ip
|
# 用环境变量获取本机ip
|
||||||
def get_local_ip():
|
def get_local_ip():
|
||||||
global ip
|
global ip
|
||||||
ip = os.environ.get("HOST_IP", "IP not set")
|
ip = os.environ.get("HOST_IP")
|
||||||
|
if not ip: # 如果环境变量中没有IP
|
||||||
|
try:
|
||||||
|
# 从网卡获取IP
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
s.connect(("8.8.8.8", 80)) # 通过连接Google DNS获取IP
|
||||||
|
ip = str(s.getsockname()[0])
|
||||||
|
s.close()
|
||||||
|
except:
|
||||||
|
raise ValueError("Unable to get IP")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def init():
|
def init():
|
||||||
|
Loading…
x
Reference in New Issue
Block a user