Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6054446
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类:

2012-12-23 07:59:38

原文地址:python获取ip地址 作者:txgc_wm

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)
阅读(734) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~