首先是获取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)])
然后是获取公网IP:
import socket
s = socket.create_connection(('ns1.dnspod.net', 6666))
print(s.recv(16))
s.close()
接着是获取内网IP的一个错误示例:
import socket
name = socket.getfqdn(socket.gethostname()) #获取本机host名
ip = socket.gethostbyname(name) #获取本机ip
print name
print ip
如果你的电脑上有多个实体网卡/虚拟网卡,那么这样子做很有可能只能获取到其中一个的IP.
如果你要获取所有的内网IP:
import socket
IPs = socket.gethostbyname_ex(socket.gethostname())[-1]
print(IPs)
如果你要获取你正在上网时所使用的内网IP:
import os
IP = [a for a in os.popen('route print').readlines() if ' 0.0.0.0 ' in a][0].split()[-2]
print IP
这里利用了路由(route)