#!/usr/bin/python

# tz_ip_adr.py
#       --copyright--                   Copyright 2013 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       September 28, 2013      bar
#       --eodstamps--
##      \file
#       \namespace              tzpython.tz_ip_adr
#
#
#       Do IP address things.
#
#

import  os
import  socket


SIOCGIFADDR         = 0x8915

get_interface_ip    = None
if  os.name != "nt" :

    import  fcntl
    import  struct


    def get_interface_ip(ifname) :
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return(socket.inet_ntoa(fcntl.ioctl(s.fileno(), SIOCGIFADDR, struct.pack('256s', ifname[:15]) )[20:24]))


    get_ip_sock     = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    get_ip_sock_fd  = get_ip_sock.fileno()

    def get_ip(iface = 'eth0') :
        ifreq   = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
        try     :
            res = fcntl.ioctl(get_ip_sock_fd, SIOCGIFADDR, ifreq)
        except  IOError :
            return(None)
        ip      = struct.unpack('16sH2x4s8x', res)[2]
        return(socket.inet_ntoa(ip))

    pass


def get_lan_ip() :
    """ Return a good guess of what our LAN ip address is. """
    adrs            = [ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ]
    ip              = (len(adrs) and adrs[0]) or None       # go with the first one
    if  (not ip) and get_interface_ip :
        interfaces  = [ "eth0", "eth1", "eth2", "eth3", "eth4", "eth5", "eth6", "eth7", "eth8", "eth9", "wlan0", "wlan1", "wifi0", "ath0", "ath1", "ppp0", ]

        for ifname in interfaces :
            try     :
                ip  = get_interface_ip(ifname)
                if  not ip.startswith("127.") :
                    break
                ip  = None
            except IOError :
                ip  = None

            if  not ip :
                ip  = get_ip(ifname)
                if  ip and (not ip.startswith("127.")) :
                    break
                ip  = None
            pass
        pass

    return(ip)


if  __name__ == '__main__' :
    print get_lan_ip()


#
#
# eof
