# coding=utf-8
from PyQt4.QtCore import QObject, QFile, QIODevice, QTextStream
from PyQt4.QtNetwork import QHostAddress


class Hostop(QObject):
    def __init__(self, parent=None):
        super(Hostop, self).__init__(parent)

    def getHostFile(self):
        if (not QFile.exists("/etc/hosts")):
            return -1
        file_con = QFile("/etc/hosts")
        if (not file_con.open(QIODevice.ReadOnly)):
            file_con.close()
            return -1
        if (file_con.size() == 0):
            file_con.close()
            return -2
        fs = QTextStream(file_con)
        hostcon = fs.readAll()
        return hostcon

    def getHostList(self):
        res = self.getHostFile()
        if (-1 == res):
            return []
        elif (-2 == res):
            return []
        elif (res == ""):
            return []

        temp = res.split("\n")
        hostList = []
        for i in range(len(temp)):
            if (temp[i].startsWith("#")):
                continue
            temp[i] = temp[i].simplified()
            str = temp[i].split(" ")
            num = len(str)
            if (num > 1):
                host = {}
                host["hostip"] = str[0]
                host["hostdes"] = str[1]
                hostList.append(host)
        return hostList


if __name__ == "__main__":
    _hostop = Hostop()


    def if_ip_address(ip_addr):
        hostIp = QHostAddress()
        if hostIp.setAddress(ip_addr):
            return True
        return False


    def get_host_addr():
        return _hostop.getHostList()


    __hostIp = 'None'

    ret = if_ip_address(__hostIp)
    if ret == True:
        host_list = get_host_addr()
        print host_list
        for i in range(len(host_list)):
            if host_list[i]["hostip"] == __hostIp:
                __hostIp = host_list[i]["hostdes"]
                break
    print ret