使用 Python 的 stdlib 查找本地 IP 地址 [英] Finding local IP addresses using Python's stdlib

查看:27
本文介绍了使用 Python 的 stdlib 查找本地 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 平台上单独使用标准库查找本地 IP 地址(即 192.168.x.x 或 10.0.x.x)?

How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

推荐答案

import socket
socket.gethostbyname(socket.gethostname())

这并不总是有效(在 /etc/hosts 中主机名为 127.0.0.1 的机器上返回 127.0.0.1),一种治标不治本的方法是 gimel 显示的,使用 socket.getfqdn() 代替.当然,您的机器需要一个可解析的主机名.

This won't work always (returns 127.0.0.1 on machines having the hostname in /etc/hosts as 127.0.0.1), a paliative would be what gimel shows, use socket.getfqdn() instead. Of course your machine needs a resolvable hostname.

这篇关于使用 Python 的 stdlib 查找本地 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆