我正在尝试将我的ip子网地址(192.168.1.xxx)放入我的python代码中.我正在运行linux/osx.我该怎么做/最好的方法是什么?
根据我的经验,最简单的方法是使用两个第三方软件包:
python-netifaces:可移植的网络接口信息
python-netaddr:对IPv4,IPv6,CIDR,EUI和MAC网络地址进行Pythonic操作
所以安装这些模块然后它就像这样简单:
import netifaces import netaddr import socket from pprint import pformat ifaces = netifaces.interfaces() # => ['lo', 'eth0', 'eth1'] myiface = 'eth0' addrs = netifaces.ifaddresses(myiface) # {2: [{'addr': '192.168.1.150', # 'broadcast': '192.168.1.255', # 'netmask': '255.255.255.0'}], # 10: [{'addr': 'fe80::21a:4bff:fe54:a246%eth0', # 'netmask': 'ffff:ffff:ffff:ffff::'}], # 17: [{'addr': '00:1a:4b:54:a2:46', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]} # Get ipv4 stuff ipinfo = addrs[socket.AF_INET][0] address = ipinfo['addr'] netmask = ipinfo['netmask'] # Create ip object and get cidr = netaddr.IPNetwork('%s/%s' % (address, netmask)) # => IPNetwork('192.168.1.150/24') network = cidr.network # => IPAddress('192.168.1.0') print 'Network info for %s:' % myiface print '--' print 'address:', address print 'netmask:', netmask print ' cidr:', cidr print 'network:', network
这输出:
Network info for eth0: -- address: 192.168.1.150 netmask: 255.255.255.0 cidr: 192.168.1.150/24 network: 192.168.1.0
这是使用Linux完成的.使用OSX,接口名称不同,但方法是相同的.