feat: get local ip from socket

This commit is contained in:
sangge 2023-11-17 09:24:20 +08:00
parent ca46f0d9d8
commit 4020213ff4
2 changed files with 22 additions and 3 deletions

View File

@ -370,8 +370,17 @@ async def receive_request(i_m: IP_Message):
def get_own_ip() -> str:
ip = os.environ.get("HOST_IP", "IP not set")
return ip
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 = s.getsockname()[0]
s.close()
except:
raise ValueError("Unable to get IP")
return str(ip)
# get node list from central server

View File

@ -42,7 +42,17 @@ def send_ip():
# 用环境变量获取本机ip
def get_local_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():