0

How do I do ip-address/netmask etc. lookup on OS X (or BSD) using the python standard library function. I'm in the middle of a process and can't make my script working on Mac. On the Linux machine, it's pretty simple:

ifname = "eth0"
SIOCGIFNETMASK = 0x891b
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.inet_ntoa(fcntl.ioctl(s.fileno(), SIOCGIFNETMASK, struct.pack('256s', ifname))[20:24])

It returns the the netmask, for example. On OS X, I get Operation not supported on socket error:

>>> import socket, fcntl, struct
>>> ifname = "en0"
>>> SIOCGIFNETMASK = 0x891b
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> socket.inet_ntoa(fcntl.ioctl(s.fileno(), SIOCGIFNETMASK, struct.pack('256s', ifname))[20:24])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 102] Operation not supported on socket
>>> 

Looks like SIOCGIFNETMASK, SIOCGIFADDR etc. offsets are different in BSD/OS X system. Any idea how do I get around this issue? Already found a couple of posts on the same sort of issue but didn't get a definitive answer. Any input would be greatly appreciated. Thanks in advance. cheers!!

MacUsers
  • 2,091
  • 3
  • 35
  • 56

1 Answers1

0

I don't have BSD system to try but hope it should work

socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', iface))[20:24])
Satish
  • 16,544
  • 29
  • 93
  • 149