获取本机ip


import socket
import struct
import fcntl

def get_ip(iface='eth0'):
"""
Use Linux SIOCGIFADDR ioctl to get the IP for the interface.
ref http://code.activestate.com/recipes/439094-get-the-ip-address
-associated-with-a-network-inter/
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', iface[:15])
)[20:24])


print get_ip("enp3s0")

主机名: hostname = socket.gethostname()
原文地址:https://www.cnblogs.com/mhc-fly/p/6867273.html