#!/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