python ip 查询代码
时间: 2023-08-06 20:12:06 浏览: 60
你可以使用 Python 中的 socket 模块来查询 IP。以下是一个示例代码:
```python
import socket
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
```
该代码将打印出主机名和 IP 地址。请注意,此代码将返回本地计算机的 IP 地址。如果你想查询其他计算机的 IP 地址,则需要在 `gethostbyname` 函数中提供该计算机的名称或 IP 地址。
相关问题
查询ip的python代码
您可以使用Python的requests库和ipip.net提供的API来查询IP地址的详细信息。以下是示例代码:
```python
import requests
ip = '1.1.1.1' # 要查询的IP地址
url = f'http://ipapi.ipip.net/find?addr={ip}'
response = requests.get(url)
if response.status_code == 200:
result = response.json()
print(result)
else:
print('查询失败')
```
执行后,将会输出查询到的IP地址的详细信息。注意:您需要在ipip.net网站上免费申请API Key并将其替换到代码中的url参数中。
python ip地址查询
如果你想查询一个特定的IP地址的相关信息,你可以使用Python中的第三方库来实现。比较常用的是 `ipwhois` 和 `requests` 库。以下是一个简单的示例代码:
```python
import requests
from ipwhois import IPWhois
# 定义要查询的IP地址
ip_address = "8.8.8.8"
# 使用 requests 库获取IP地址的详细信息
response = requests.get(f"http://ip-api.com/json/{ip_address}")
if response.status_code == 200:
# 使用 ipwhois 库获取IP地址的 whois 信息
ipwhois = IPWhois(ip_address)
whois_info = ipwhois.lookup_rdap()
# 输出IP地址的详细信息和whois信息
print("IP地址详细信息:")
print(response.json())
print("IP地址whois信息:")
print(whois_info)
else:
print("查询失败")
```
运行以上代码将输出IP地址的详细信息和whois信息。注意,查询IP地址的whois信息需要使用 `ipwhois` 库,而非 `requests` 库。