曾经写过一个脚本在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()