在Python中获取当前网络IP地址,可以通过以下几种方法:
1. 使用`socket`模块获取内网IP地址:
import socketdef get_local_ip():hostname = socket.gethostname()local_ip = socket.gethostbyname(hostname)return local_ipprint("本机内网IP地址为:", get_local_ip())
2. 使用`socket`模块连接外网地址获取公网IP地址:
import socketdef get_public_ip():try:s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.connect(('8.8.8.8', 80))ip = s.getsockname()s.close()return ipexcept socket.error:return "获取公网IP地址失败"print("本机公网IP地址为:", get_public_ip())

3. 使用第三方库`netifaces`获取所有网络接口的IP地址:
import netifacesdef get_all_ips():ip_list = []for interface in netifaces.interfaces():addrs = netifaces.ifaddresses(interface)for address in addrs:if address['family'] == netifaces.AF_INET:ip_list.append(address['addr'])return ip_listprint("本机所有IP地址为:", get_all_ips())
4. 使用`requests`库访问特定网站获取公网IP地址:
import requestsdef get_public_ip_from_website():try:response = requests.get('http://ifconfig.me/ip', timeout=1)return response.text.strip()except requests.exceptions.RequestException:return "获取公网IP地址失败"print("本机公网IP地址为:", get_public_ip_from_website())
