3

I'm trying to get my ip subnet address (192.168.1.xxx) into my python code. I'm running linux/osx. How do I do this/ What is the best way to do this?

tallowen
  • 4,198
  • 7
  • 27
  • 35
  • 2
    possible duplicate of [Finding local IP addresses in Python.](http://stackoverflow.com/questions/166506/finding-local-ip-addresses-in-python) – Mark Sep 20 '10 at 22:12

1 Answers1

9

The easiest way to to this in my experience is to use two third party packages:

So install those modules and then it's as easy as this:

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

And this outputs:

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

This was done using Linux. With OSX the interface names are different but the method is the same.

jathanism
  • 33,067
  • 9
  • 68
  • 86
  • This is erroring out on 'ipinfo = addrs[socket.AF_INET][0]' am I doing something wrong? – tallowen Sep 21 '10 at 18:24
  • Possibly. What is the error? Did you remember to `import socket`? – jathanism Sep 21 '10 at 19:13
  • Ahh, this is exactly what I was looking for. The netaddr documentation doesn't show the netaddr.IPNetwork('%s/%s' % (address, netmask)) constructor signature. – crempp May 07 '14 at 00:49