Python获取主机ip与hostname的⽅法
->基础环境
Linux:ubuntu 16.04Python ; 2.7->修改hostname
1:$sudo hostname 2tong-slavetwo2:$sudo vi /etc/hostname 2tong-slavetwo3:$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 hostname2tong-slavetwo
>>>ip = socket.gethostbyname(hostname)>>>print ip127.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的⽅法就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。