Python 獲取本地IP ,使用第三方庫,比如 netifaces
import netifaces as nidef get_ip_address():try:# 獲取默認網絡接口(通常是 'eth0' 或 'en0')default_interface = ni.gateways()['default'][ni.AF_INET][1]# 獲取指定網絡接口的IP地址ip_address = ni.ifaddresses(default_interface)[ni.AF_INET][0]['addr']except Exception as e:print(f"Error: {e}")ip_address = Nonereturn ip_address# 獲取本機IP地址
my_ip = get_ip_address()if my_ip:print(f"My IP address is {my_ip}")
else:print("Unable to determine the IP address.")
Python 獲取廣域網 IP ,通過訪問支持獲取廣域網IP的網站來獲取
import socketdef get_wan_ip():try:# 使用 socket 獲取本機IPs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.connect(('8.8.8.8', 80))local_ip = s.getsockname()[0]s.close()# 使用 DNS 查詢獲取廣域網IPwan_ip = socket.gethostbyname(socket.gethostname())# 比較本機IP和廣域網IP,如果相同,則使用外部服務獲取廣域網IPif local_ip == wan_ip:external_ip_service = 'http://api.ipify.org'response = requests.get(external_ip_service)wan_ip = response.textexcept Exception as e:print(f"Error: {e}")wan_ip = Nonereturn wan_ip# 獲取廣域網IP地址
my_wan_ip = get_wan_ip()if my_wan_ip:print(f"My WAN IP address is {my_wan_ip}")
else:print("Unable to determine the WAN IP address.")
import requestsdef get_wan_ip():try:# 使用一個公共的 IP 地址查詢服務response = requests.get('https://api64.ipify.org?format=json')data = response.json()# 獲取廣域網 IP 地址wan_ip = data['ip']except Exception as e:print(f"Error: {e}")wan_ip = Nonereturn wan_ip# 獲取廣域網 IP 地址
my_wan_ip = get_wan_ip()if my_wan_ip:print(f"My WAN IP address is {my_wan_ip}")
else:print("Unable to determine the WAN IP address.")