博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 获取本机ip地址
阅读量:6970 次
发布时间:2019-06-27

本文共 1787 字,大约阅读时间需要 5 分钟。

  hot3.png

# -*- coding=utf-8 -*-# Created Time: 2017年02月27日 星期一 09时08分31秒# File Name: get_mac_address.pyimport uuidimport socketimport fcntlimport structdef get_host_attr():    attr = {        "mac"     :"",        "hostname":"",        "ip"      :""    }    try:        mac=uuid.UUID(int = uuid.getnode()).hex[-12:]        mac = ":".join([mac[e:e+2] for e in range(0,11,2)])    except:        pass    #获取本机电脑名    try:        hostname = socket.getfqdn(socket.gethostname())    except:        pass    #获取本机ip    try:        ip = socket.gethostbyname(hostname)    except:        pass    attr.update({        "mac"     :mac,        "hostname":hostname,        "ip"      :ip    })    print 'attr: ', attr    ip_list = socket.gethostbyname_ex(socket.gethostname())    print 'ip_list: ', ip_listdef get_ip_address(ifname):    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    ip = socket.inet_ntoa(fcntl.ioctl(        s.fileno(),        0x8915,  # SIOCGIFADDR        struct.pack('256s', ifname[:15])    )[20:24])    print 'ip: ', ipdef 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"def main():    get_host_attr()    get_ip_address('eth0')    ip = get_my_ip()    print 'ip: ', ipif __name__ == '__main__':    main()

 

转载于:https://my.oschina.net/bwhite/blog/846943

你可能感兴趣的文章
POJ 1743 Musical Theme(不可重叠最长重复子串)
查看>>
使用JPA储存Text类型的时候 出现乱码的问题
查看>>
cisco ssh配置
查看>>
高性能页面加载技术--BigPipe设计原理及Java简单实现
查看>>
Angular 选项卡
查看>>
设计模式之工厂方法模式
查看>>
Cap25_量化的项目管理
查看>>
iOS 使用xib定义一个View,修改frame无效问题解决
查看>>
用JavaScript获取页面上被选中的文字的技巧
查看>>
Hadoop(3)---如何构建HDFS--HA,YARN---HA
查看>>
hbase region超时问题
查看>>
PAT_A1034#Head of a Gang
查看>>
【Python基础】lpthw - Exercise 38 列表的操作
查看>>
多线程交叉运行思考
查看>>
Kafka管理工具介绍
查看>>
Microsoft Dynamics AX 2012 Resources Quick Reference
查看>>
Create Linux VM form
查看>>
spring的官方文真不错
查看>>
min-width,min-height,overflow,移动端
查看>>
消防给水(三)
查看>>