However, the output of the ʻifconfig command and the ʻip
command should not be parsed.
On Linux, you can get it with ʻioctl (SIOCGIFADDR) `.
It is almost the same as the script of the source (Reference 1 below). With Python, it's easy because you can write so far with the distribution attached.
import sys, socket, struct
from fcntl import ioctl
SIOCGIFADDR = 0x8915
if len(sys.argv) < 2:
print >> sys.stderr, "Usage:", sys.argv[0], "<interface name>"
sys.exit()
interface = sys.argv[1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
ifreq = struct.pack('16s16x', interface)
ifaddr = ioctl(s.fileno(), SIOCGIFADDR, ifreq)
finally:
s.close()
_, sa_family, port, in_addr = struct.unpack('16sHH4s8x', ifaddr)
print socket.inet_ntoa(in_addr)
Recommended Posts