曾经写过一个脚本在Linux系统上来获得本地的IP地址:

#!/usr/bin/env python

import socket
import struct
import fcntl
import sys

def getip(ethname):
    if ethname=="":
        ethname="eth0"
    try:
        s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ip=socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0X8915, struct.pack('256s', ethname[:15]))[20:24])
    except:
        ip=""
    return ip

if __name__=='__main__':
    print getip("")
    print getip("eth0")

上面的脚本由于用到了fcntl,无法在Windows上使用,因此使用下面的方法在两个系统上都可以正常使用:

#!/usr/bin/env python

import socket

def getip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('www.baidu.com', 0))
        ip=s.getsockname()[0]
    except:
        ip=""
    finally:
        s.close()
    return ip

if __name__=='__main__':
    print getip()

相关文章:

  • 2021-08-27
  • 2022-12-23
  • 2022-01-07
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-18
  • 2021-09-21
  • 2021-12-05
  • 2022-12-23
  • 2021-11-27
  • 2022-12-23
相关资源
相似解决方案