import datetime
import socket
def get_ip_and_time():
"""
获取当前 IP 地址和当前时间。
Returns:
tuple: 包含 IP 地址 (str) 和格式化时间字符串 (str) 的元组。
如果无法获取IP地址,则IP地址为 "N/A"。
"""
try:
# 获取本机主机名
hostname = socket.gethostname()
# 获取本机 IP 地址
ip_address = socket.gethostbyname(hostname)
except socket.gaierror: # 处理可能出现的无法解析主机名的情况
ip_address = "N/A"
except Exception as e: # 处理其他可能出现的异常
print(f"Error getting IP address: {e}")
ip_address = "N/A"
# 获取当前时间
now = datetime.datetime.now()
# 格式化时间字符串 (例如: 2023-10-27 10:30:45)
formatted_time
= now.
strftime("%Y-%m-%d %H:%M:%S")
return ip_address, formatted_time
def get_external_ip():
"""
获取公网IP地址 (通过访问外部服务)。
更可靠的获取公网ip的方式,但需要网络连接。
Returns:
str: 公网IP地址。如果无法获取,返回 "N/A".
"""
try:
import requests # 导入 requests 库 (如果尚未导入)
# 使用多个服务来提高可靠性。如果一个失败,尝试下一个。
services = [
"https://a...content-available-to-author-only...y.org",
"https://i...content-available-to-author-only...p.com",
"https://i...content-available-to-author-only...t.me",
"https://i...content-available-to-author-only...o.io/ip"
# 可以添加更多服务
]
for service in services:
try:
response = requests.get(service, timeout=5) #设置超时时间
response.raise_for_status() # 检查是否有HTTP错误 (4xx 或 5xx)
external_ip = response.text.strip()
return external_ip
except requests.exceptions.RequestException as e: # 捕获各种请求异常
print(f"Error getting external IP from {service}: {e}")
continue #尝试下一个服务
return "N/A" #所有服务都失败了
except ImportError:
print("requests library not found. Please install it: pip install requests")
return "N/A"
except Exception as e: #处理其他未预料到的异常
print(f"An unexpected error occurred: {e}")
return "N/A"
if __name__ == "__main__":
ip
, time = get_ip_and_time
() print(f"Local IP Address: {ip}")
print(f"Current Time: {time}")
external_ip = get_external_ip()
print(f"External IP Address: {external_ip}")