Linux
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
#get_ip_address('lo')环回地址
#get_ip_address('eth0')主机ip地址
windows
import re,urllib2
from subprocess import Popen, PIPE
print "本机的私网IP地址为:" + re.search('\d+\.\d+\.\d+\.\d+',Popen('ipconfig', stdout=PIPE).stdout.read()).group(0)
print "本机的公网IP地址为:" + re.search('\d+\.\d+\.\d+\.\d+',urllib2.urlopen("http://www.7qiao.cn/ip.php").read()).group(0)
本文提供了一种在Linux和Windows系统中获取IP地址的方法。对于Linux系统,使用Python的socket和fcntl模块来获取环回地址和主机IP地址;对于Windows系统,则通过调用ipconfig命令并解析其输出来获取私网IP地址,并通过访问特定网站获取公网IP地址。

被折叠的 条评论
为什么被折叠?



