获取本机所有网卡的 IP 地址:

  1. IPs = socket.gethostbyname_ex(socket.gethostname())[-1]

获取正在上网的本机网卡 IP 地址:

WIndows:

  1. [a for a in os.popen('route print').readlines() if ' 0.0.0.0 ' in a][0].split()[-2]

Linux:

  1. os.popen("ifconfig | grep inet").readlines()[0].strip().split(' ')[1]

优雅的获取 IP(推荐)

  1. import socket
  2. def get_host_ip():
  3. try:
  4. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  5. s.connect(('8.8.8.8', 80))
  6. ip = s.getsockname()[0]
  7. finally:
  8. s.close()
  9. return ip