1. 使用`socket`库:
import socketdef get_local_ip():hostname = socket.gethostname()local_ip = socket.gethostbyname(hostname)return local_ipdef get_public_ip():try:response = requests.get('http://httpbin.org/ip')data = response.json()ip = data['origin']return ipexcept requests.exceptions.RequestException:return '获取公网IP失败'获取本机IP地址local_ip = get_local_ip()print('本地IP地址为:', local_ip)获取公网IP地址public_ip = get_public_ip()print('公网IP地址为:', public_ip)
2. 使用第三方库`netifaces`:

import netifacesdef get_local_ip():for interface in netifaces.interfaces():addresses = netifaces.ifaddresses(interface)for address in addresses:if address['family'] == netifaces.AF_INET and not address['addr'].startswith('127.'):return address['addr']return '无法获取本地IP地址'获取本机IP地址local_ip = get_local_ip()print('本地IP地址为:', local_ip)
3. 使用第三方服务API获取公网IP:
import requestsdef get_public_ip():try:response = requests.get('http://myip.ipip.net')return response.text.strip()except requests.exceptions.RequestException:return '获取公网IP失败'获取公网IP地址public_ip = get_public_ip()print('公网IP地址为:', public_ip)
以上代码示例展示了如何使用Python获取本地和公网IP地址。请根据您的需求选择合适的方法
