Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1734264
  • 博文数量: 234
  • 博客积分: 4966
  • 博客等级: 上校
  • 技术积分: 3322
  • 用 户 组: 普通用户
  • 注册时间: 2006-11-13 01:03
文章分类

全部博文(234)

文章存档

2017年(2)

2016年(1)

2015年(8)

2014年(11)

2013年(44)

2012年(27)

2011年(22)

2010年(30)

2009年(37)

2008年(6)

2007年(45)

2006年(1)

分类: Python/Ruby

2013-09-08 23:05:40

用python获取本机IP地址[in  Linux]

方法一:【最好的一个,<推荐>
可以不必知道使用的是哪个网络设备,十分方便的获得正在使用的IP地址!
#!/usr/bin/env python
import socket
def get_my_ip():
    """
    Returns the actual ip of the local machine.
    This code figures out what source address would be used if some traffic
    were to be sent out to some well known address on the Internet. In this
    case, a Google DNS server is used, but the specific address does not
    matter much.  No traffic is actually sent.
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('8.8.8.8', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1"

if __name__ == "__main__":
    print get_my_ip()

方法二:【最灵活的一个】
需要指明此时正在使用的网络设备名!
#!/usr/bin/env python

import socket
import fcntl
import struct
 
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

Local_ip=get_ip_address("xxx")#xxx表示网络设备名
阅读(5427) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~