import socket
import fcntl
import struct


def _getIP(ifname):
    """ Get the IP address associated with a network interface.

        Based on:
            http://code.activestate.com/recipes/439094-get-the-ip-address-
            associated-with-a-network-inter/

            PSF License (Python Software Foundation)

        @param ifname:          The name of the network interface for which the
                                IP address should be retrieved.
        @type  finame:          str

        @return:                IP address as a string, i.e. x.x.x.x
        @rtype:                 str
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    try:
        return socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15])
        )[20:24])
    except IOError:
        raise ValueError("Either the interface '{0}' isn't connected or there "
                         "seems to be a network error".format(ifname))