添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
耍酷的芹菜  ·  [Python] async def & ...·  1 月前    · 
乐观的竹笋  ·  如何快速上手MuJoCo ...·  1 月前    · 
着急的跑步鞋  ·  Python ...·  1 月前    · 
年轻有为的海龟  ·  使用Python ...·  4 周前    · 
幸福的墨镜  ·  macbook python ...·  3 周前    · 
无邪的松树  ·  log4j ...·  2 年前    · 
潇洒的电梯  ·  jQuery.globalEval()方法 ...·  2 年前    · 
果断的鸵鸟  ·  与 MySQL 兼容性对比 | ...·  2 年前    · 
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >>> s.connect(('8.8.8.8', 80)) >>> ip = s.getsockname()[0] '192.168.1.3'
>>> import socket
>>> hostname = socket.gethostname()
>>> ip_lists = socket.gethostbyname_ex(hostname)
>>> ip_lists
('USER-20150331GI', [], ['192.168.1.3'])
>>> # 获取主机名
>>> hostname = ip_lists[0]
>>> hostname
'USER-20150331GI'
>>> # 获取IP地址
>>> ip = lst[-1]
['192.168.1.3']
方法一:>>> import socket>>> # 获取主机名>>> hostname = socket.gethostname()>>> hostname'USER-20150331GI'>>>>>> # 获取IP地址>& mac=uuid.UUID(int=uuid.getnode()).hex[-12:] return":".join([mac[e:e+2]foreinrange(0,11,2)])
比如我的hosts名字 [root@controller ~]# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 99.0.85.37 controller 99.0.85.38 compute1 99.0.85
一般情况下使用socket.gethostbyname()的 方式 就可以 获取 本机 IP地址 ,不排除偶尔的时候 获取 不到(比如没有正确设置 主机名 称),示例代码如下: import socket 获取 本计算机的名称 hostname = socket.gethostname() 获取 本计算机 IP ip = socket.gethostbyname(hostname) print( ip )
python 获取 主机 ip Python socket module can be used to get the IP address from a hostname. Python 套接字模块可用于从 主机名 获取 IP地址 。 The socket module is part of the Python core libraries, so we don’t need to install it se...