ITPub博客

首页 > 数据库 > MySQL > 【Python】获取主机ip的方式

【Python】获取主机ip的方式

原创 MySQL 作者:杨奇龙 时间:2016-02-02 10:41:53 0 删除 编辑
最近写后台业务逻辑,要用到获取本机ip地址的方法,记录两个python的实现方式:

  1. import socket
  2. import struct
  3. import fcntl
  4. import commands

  5. def getLocalIP():
  6.     status,output=commands.getstatusoutput("hostname -i")
  7.     if status :
  8.      return '127.0.0.1'
  9.     else :
  10.      return output

  11. def getip(ethname):
  12.     s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  13.     return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0X8915, struct.pack('256s', ethname[:15]))[20:24])

  14. if __name__=='__main__':
  15.    print "getip :" , getip('eth0')
  16.    print "getLocalIP :", getLocalIP()
注意 本案例中 我写的是 eth0 ,  如果是生产环境做了网卡绑定的话 需要使用 getip(bond0)
执行结果
  1. [yangyidba@rac3 10:31:12 ~]
  2. $ python getip.py
  3. getip      : 10.10.15.12
  4. getLocalIP : 10.10.15.12

还有shell 的实现方式, 可以使用 以下shell 方式 替代python 实现中的  hostname -i :

  1. host `hostname --fqdn` 2>/dev/null | awk '{print $NF}'
  2. 10.10.15.12

  3. ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"
  4. 10.10.15.12

  5. ifconfig|grep -v "127.0.0.1" | sed -n '/inet addr/s/^[^:]*:\([0-9.]\{7,15\}\) .*/\1/p'
  6. 10.10.15.12


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/22664653/viewspace-1985495/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
MySQL DBA NoSQL DEVOPS

注册时间:2009-10-07

  • 博文量
    1026
  • 访问量
    8205955