python获取ip地址

1510阅读 0评论2013-10-17 dba_life
分类:Python/Ruby

python获取ip地址代码:
  1. #!/usr/bin/python
  2. #conding:utf-8
  3.   
  4. import socket,fcntl,struct

  5. def get_ip_address(ifname):
  6.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  7.     return socket.inet_ntoa(fcntl.ioctl(
  8.                 s.fileno(),
  9.                 0x8915, # SIOCGIFADDR
  10.                 struct.pack('256s', ifname[:15])
  11.                 )[20:24])
  12.      
  13. print get_ip_address('lo')
  14. print get_ip_address('wlan0')

执行结果:
  1. $ python getip.py
  2. 127.0.0.1
  3. 192.168.2.102

本机信息:
  1. $ ifconfig

  2. lo Link encap:Local Loopback
  3. inet addr:127.0.0.1 Mask:255.0.0.0
  4. inet6 addr: ::1/128 Scope:Host
  5. UP LOOPBACK RUNNING MTU:16436 Metric:1
  6. RX packets:35657 errors:0 dropped:0 overruns:0 frame:0
  7. TX packets:35657 errors:0 dropped:0 overruns:0 carrier:0
  8. collisions:0 txqueuelen:0
  9. RX bytes:3487215 (3.4 MB) TX bytes:3487215 (3.4 MB)

  10. wlan0 Link encap:Ethernet HWaddr 20:7c:8f:69:f2:b5
  11. inet addr:192.168.2.102 Bcast:192.168.2.255 Mask:255.255.255.0
  12. inet6 addr: fe80::227c:8fff:fe69:f2b5/64 Scope:Link
  13. UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
  14. RX packets:14399 errors:0 dropped:0 overruns:0 frame:0
  15. TX packets:17826 errors:0 dropped:0 overruns:0 carrier:0
  16. collisions:0 txqueuelen:1000
  17. RX bytes:6866206 (6.8 MB) TX bytes:2687637 (2.6 MB)
上一篇:主从复制的问题
下一篇:ubuntu安装和查看已安装