fork download
  1. import datetime
  2. import socket
  3.  
  4. def get_ip_and_time():
  5. """
  6. 获取当前 IP 地址和当前时间。
  7.  
  8. Returns:
  9. tuple: 包含 IP 地址 (str) 和格式化时间字符串 (str) 的元组。
  10. 如果无法获取IP地址,则IP地址为 "N/A"。
  11. """
  12. try:
  13. # 获取本机主机名
  14. hostname = socket.gethostname()
  15. # 获取本机 IP 地址
  16. ip_address = socket.gethostbyname(hostname)
  17. except socket.gaierror: # 处理可能出现的无法解析主机名的情况
  18. ip_address = "N/A"
  19. except Exception as e: # 处理其他可能出现的异常
  20. print(f"Error getting IP address: {e}")
  21. ip_address = "N/A"
  22.  
  23.  
  24.  
  25. # 获取当前时间
  26. now = datetime.datetime.now()
  27.  
  28. # 格式化时间字符串 (例如: 2023-10-27 10:30:45)
  29. formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
  30.  
  31. return ip_address, formatted_time
  32.  
  33.  
  34. def get_external_ip():
  35. """
  36. 获取公网IP地址 (通过访问外部服务)。
  37. 更可靠的获取公网ip的方式,但需要网络连接。
  38.  
  39. Returns:
  40. str: 公网IP地址。如果无法获取,返回 "N/A".
  41. """
  42. try:
  43. import requests # 导入 requests 库 (如果尚未导入)
  44.  
  45. # 使用多个服务来提高可靠性。如果一个失败,尝试下一个。
  46. services = [
  47. "https://a...content-available-to-author-only...y.org",
  48. "https://i...content-available-to-author-only...p.com",
  49. "https://i...content-available-to-author-only...t.me",
  50. "https://i...content-available-to-author-only...o.io/ip"
  51. # 可以添加更多服务
  52. ]
  53. for service in services:
  54. try:
  55. response = requests.get(service, timeout=5) #设置超时时间
  56. response.raise_for_status() # 检查是否有HTTP错误 (4xx 或 5xx)
  57. external_ip = response.text.strip()
  58. return external_ip
  59. except requests.exceptions.RequestException as e: # 捕获各种请求异常
  60. print(f"Error getting external IP from {service}: {e}")
  61. continue #尝试下一个服务
  62. return "N/A" #所有服务都失败了
  63.  
  64. except ImportError:
  65. print("requests library not found. Please install it: pip install requests")
  66. return "N/A"
  67. except Exception as e: #处理其他未预料到的异常
  68. print(f"An unexpected error occurred: {e}")
  69. return "N/A"
  70. if __name__ == "__main__":
  71. ip, time = get_ip_and_time()
  72. print(f"Local IP Address: {ip}")
  73. print(f"Current Time: {time}")
  74.  
  75. external_ip = get_external_ip()
  76. print(f"External IP Address: {external_ip}")
Success #stdin #stdout 0.37s 27744KB
stdin
Standard input is empty
stdout
Local IP Address: N/A
Current Time: 2025-02-11 09:08:49
Error getting external IP from https://a...content-available-to-author-only...y.org: HTTPSConnectionPool(host='api.ipify.org', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x14a8c8988588>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))
Error getting external IP from https://i...content-available-to-author-only...p.com: HTTPSConnectionPool(host='icanhazip.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x14a8c8988518>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))
Error getting external IP from https://i...content-available-to-author-only...t.me: HTTPSConnectionPool(host='ident.me', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x14a8c89885f8>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))
Error getting external IP from https://i...content-available-to-author-only...o.io/ip: HTTPSConnectionPool(host='ipinfo.io', port=443): Max retries exceeded with url: /ip (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x14a8c89880f0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution'))
External IP Address: N/A