Python 获取本机ip地址
Python 获取本机ip地址
扫把就是扫把 发表于10个月前
Python 获取本机ip地址
  • 发表于 10个月前
  • 阅读 29
  • 收藏 2
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

# -*- coding=utf-8 -*-
# Created Time: 2017年02月27日 星期一 09时08分31秒
# File Name: get_mac_address.py


import uuid
import socket
import fcntl
import struct


def 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_list



def 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: ', ip


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"


def main():

    get_host_attr()

    get_ip_address('eth0')

    ip = get_my_ip()
    print 'ip: ', ip


if __name__ == '__main__':
    main()

 

共有 人打赏支持
粉丝 2
博文 29
码字总数 23616
×
扫把就是扫把
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: