# -*- coding=utf-8 -*-# Created Time: 2017年02月27日 星期一 09时08分31秒# File Name: get_mac_address.pyimport uuidimport socketimport fcntlimport structdef 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_listdef 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: ', ipdef 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: ', ipif __name__ == '__main__': main()