在Python中获取IP地址可以通过以下几种方法:
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地址。请根据您的需求选择合适的方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/114851.html