获取本机IP、mac地址、计算机名

python获取本机IP、mac地址、计算机名

在python中获取ip地址和在php中有很大不同,我们先来看一下python 获得本机MAC地址:

>>> import uuid

>>> def get_mac_address():

            mac = uuid.UUID(int = uuid.getnode()).hex[-12:]

            return ':'.join([mac[e:e+2] for e in range(0,11,2)])

>>> get_mac_address()

'a4:be:6d:99:87:db'

下面再来看一下python获取IP的方法:使用socket

>>> import socket

>>> hostname = socket.getfqdn(socket.gethostname( ))

>>> print(hostname)

USER-20160730ZR

>>> hostaddr = socket.gethostbyname(hostname)

>>> print(hostaddr)

192.168.217.1

但是注意这里获取的IP是内网IP

方法二:在linux下可用,window无效

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])

  

>>> get_ip_address('lo')

'127.0.0.1'

  

>>> get_ip_address('eth0')

'38.113.228.130'

原文地址:https://www.cnblogs.com/-simon/p/5887610.html