->基础环境
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 获取主机ip与hostname的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。