python获取本地ip地址的方法

时间:2021-08-06 05:55:18
#_*_coding:utf8_*_

#以下两种方法可以在ubuntu下或者windows下获得本地的IP地址
import socket # 方法一
localIP = socket.gethostbyname(socket.gethostname())
print ("local ip address: %s"%localIP) ipList = socket.gethostbyname_ex(socket.gethostname()) # 循环打印
for i in ipList:
if i != localIP:
print "Other ip address: %s"%i # 方法二
print("获得本地IP地址的第二中方法") ipname = socket.getfqdn(socket.gethostname())
myaddress = socket.gethostbyname(ipname)
print myaddress 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])