python3获取本机ip_python机考

python3获取本机ip_python机考在 Python 中查询本机 IP 地址 可以使用以下几种方法 1 使用 socket 模块 pythonimport socketdef get local ip hostname socket gethostname local ip socket gethostbynam hostname return local ip print 本机 IP 地址为

在Python中查询本机IP地址,可以使用以下几种方法:

1. 使用`socket`模块:

python

import socket

def get_local_ip():

hostname = socket.gethostname()

local_ip = socket.gethostbyname(hostname)

return local_ip

print("本机IP地址为:", get_local_ip())

2. 使用`socket`模块创建UDP连接到外部服务(如Google的DNS服务器8.8.8.8)来获取IP地址:

python

import socket

def get_ip_address():

try:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.connect(("8.8.8.8", 80))

ip_address = s.getsockname()

s.close()

return ip_address

except socket.error:

return "获取IP地址失败"

print("本机IP地址为:", get_ip_address())

3. 使用第三方库`netifaces`来获取网络接口的IP地址:

python

import netifaces

def get_ip_address():

for interface in netifaces.interfaces():

addresses = netifaces.ifaddresses(interface)

for address in addresses:

if address['family'] == netifaces.AF_INET and address['addr'] != '127.0.0.1':

return address['addr']

return "无法获取IP地址"

print("本机IP地址为:", get_ip_address())

以上方法可以帮助你获取本机在局域网内的IP地址。如果你需要获取公网IP地址,可以使用如下代码:

python

import requests

def get_public_ip():

try:

response = requests.get("https://api.ipify.org", timeout=5)

return response.text

except requests.exceptions.RequestException:

return "无法获取公网IP地址"

print("公网IP地址为:", get_public_ip())

请选择适合你需求的方法进行尝试

编程小号
上一篇 2026-04-13 23:42
下一篇 2026-04-13 23:36

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/57866.html