咱們先來看一下python 得到本機MAC地址:node
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)])
下面再來看一下python獲取IP的方法:使用socketpython
import socket #獲取本機電腦名 myname = socket.getfqdn(socket.gethostname( )) #獲取本機ip myaddr = socket.gethostbyname(myname) print myname print myaddr
可是注意這裏獲取的IP是內網IPlinux
方法三:在linux下可用socket
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') '10.0.3.249'