Python 获取主机ip与hostname的方法
->基础环境
Linux:ubuntu 16.04
Python ; 2.7
->修改hostname
1:$sudo hostname 2tong-slavetwo
2:$sudo vi /etc/hostname
2tong-slavetwo
3:$sudo vi /etc/hosts
127.0.0.1 localhost 2tong-slavetwo
127.0.1.1 2tong-slavetwo
->Python 环境下输出ip hostname
>>>import socket
>>>hostname = socket.gethostname()
>>>print hostname
2tong-slavetwo
>>>ip = socket.gethostbyname(hostname)
>>>print ip
127.0.0.1
>>>ipList = socket.gethostbyname_ex(name)
>>>print ipList
('localhost', ['2tong-slavetwo', '2tong-slavetwo'], ['127.0.0.1', '127.0.1.1']
->札记
import socket后,会从/etc/hostname中寻找hostname,而后前往/etc/hosts中查找ip
上一篇:python爬虫开发之Request模块从安装到详细使用方法与实例全解
栏 目:Python代码
本文标题:Python 获取主机ip与hostname的方法
本文地址:http://www.codeinn.net/misctech/41611.html