#!/usr/bin/env python?
'''
根據 設備名(br0/eth0/em0)稱獲取 當前機器的IP地址與子網掩碼信息
'''
import socket, struct, fcntl
def get_ipaddress(ifname = 'eth0'):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, ?# SIOCGIFADDR
struct.pack('24s',ifname))[20:24])
def get_netmask(ifname = 'eth0'):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x891b, ?#SIOCGIFNETMASK
struct.pack('24s',ifname))[20:24])
print get_ipaddress('eth0')
print get_netmask('eth0')
本文轉自 swq499809608 51CTO博客,原文鏈接:http://blog.51cto.com/swq499809608/1130673