-simon

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\'

 

分类:

技术点:

相关文章:

  • 2021-09-12
  • 2021-06-19
  • 2022-12-23
  • 2021-05-26
  • 2021-07-20
  • 2021-08-31
猜你喜欢
  • 2021-11-24
  • 2021-12-02
  • 2021-05-26
  • 2021-09-17
相关资源
相似解决方案