python 获取内网ip对应公网ip
时间: 2024-09-22 14:00:40 浏览: 41
Python之自动获取公网IP的实例讲解
在Python中,获取内网IP对应到公网IP通常需要用到第三方库,比如`requests`、`socket`或`fping`等。以下是一个基本的例子,通过发送GET请求到外部网站来获取公共IP:
```python
import requests
def get_public_ip():
try:
response = requests.get('https://ifconfig.co')
if response.status_code == 200:
public_ip = response.text.split('\n')[0]
return public_ip
else:
raise Exception("Failed to get IP address")
except Exception as e:
print(f"Error: {str(e)}")
print(get_public_ip())
```
然而这种方式可能会遇到网络限制或服务器返回错误的情况。另一种常见做法是使用`socket`模块来查询网络信息,但这需要计算机连接到互联网:
```python
import socket
def get_public_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# 这里尝试连接Google DNS,如果成功则返回公网IP
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
except (ConnectionRefusedError, OSError):
ip = '127.0.0.1' # 如果无法连接,则可能是内网IP
finally:
s.close()
return ip
print(get_public_ip())
```
阅读全文