예제 #1
0
def _is_url_dns(urlstr):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as a string.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    url = qurl_from_user_input(urlstr)
    assert url.isValid()

    if (utils.raises(ValueError, ipaddress.ip_address, urlstr)
            and not QHostAddress(urlstr).isNull()):
        log.url.debug("Bogus IP URL -> False")
        # Qt treats things like "23.42" or "1337" or "0xDEAD" as valid URLs
        # which we don't want to.
        return False

    host = url.host()
    if not host:
        log.url.debug("URL has no host -> False")
        return False
    log.url.debug("Doing DNS request for {}".format(host))
    info = QHostInfo.fromName(host)
    return not info.error()
예제 #2
0
 def comboboxInit(self):
     # 工具选择框combox
     self.widgetui.comboBoxStyle.insertItem(0, "UDP")
     self.widgetui.comboBoxStyle.insertItem(1, "TCP Client")
     self.widgetui.comboBoxStyle.insertItem(2, "TCP Server")
     self.widgetui.comboBoxStyle.insertItem(3, "COM Tool")
     self.connectModeList = list()
     self.connectModeList.append('UDP')
     self.connectModeList.append('TCP Client')
     self.connectModeList.append('TCP Server')
     self.connectModeList.append('COM Tool')
     self.widgetui.comboBoxStyle.activated.connect(self.comboxClicked)
     # 波特率combox
     self.widgetui.comboBoxBaud.insertItems(0, baudList)
     self.widgetui.comboBoxBaud.setCurrentText("9600")
     self.widgetui.comboBoxBaud.hide()
     self.widgetui.comboComNum.hide()
     self.widgetui.comboBoxClientList.hide()  # tcp的server专用的组合框
     # 本地IP combobox
     self.myhostInfo = QHostInfo.fromName(QHostInfo.localHostName())
     hostIpList = ICommunicateTCPIP.getLocalIpList()
     if '127.0.0.1' not in hostIpList:
         hostIpList.append('127.0.0.1')
     oldHostIp = str(self.myconfig.getValue("hostIp"))
     tempHostIp = str()
     for ip in hostIpList:
         self.widgetui.comboBoxLocal.addItem(ip)
         if oldHostIp == ip:
             tempHostIp = ip
     self.widgetui.comboBoxLocal.setCurrentText(tempHostIp)
     self.myaddress = self.widgetui.comboBoxLocal.currentText()
예제 #3
0
def _is_url_dns(urlstr):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as a string.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    url = qurl_from_user_input(urlstr)
    assert url.isValid()

    if (utils.raises(ValueError, ipaddress.ip_address, urlstr) and
            not QHostAddress(urlstr).isNull()):
        log.url.debug("Bogus IP URL -> False")
        # Qt treats things like "23.42" or "1337" or "0xDEAD" as valid URLs
        # which we don't want to.
        return False

    host = url.host()
    if not host:
        log.url.debug("URL has no host -> False")
        return False
    log.url.debug("Doing DNS request for {}".format(host))
    info = QHostInfo.fromName(host)
    return not info.error()
    def run(self):
        localHostName = QHostInfo.localHostName()
        hostinfo = QHostInfo.fromName(localHostName)
        listaddress = hostinfo.addresses()

        for address in listaddress:
            if QHostAddress(
                    address).protocol() == QAbstractSocket.IPv4Protocol:
                address = QHostAddress(address).toString()
        print(address)

        host_info = ""
        confList = QNetworkConfigurationManager().allConfigurations()
        print("confList = ", confList.__len__())
        for conf in confList:
            if str(conf.bearerTypeName()) == "Ethernet":
                host_info += "\n"
                host_info += "name : " + QNetworkConfiguration(
                    conf).name() + "\n"
                host_info += str(QNetworkConfiguration(conf).isValid()) + "\n"
                host_info += "bearerType: " + QNetworkConfiguration(
                    conf).bearerTypeName() + "\n"

        list = QNetworkInterface.allInterfaces()
        for interface in list:
            host_info += "\n"
            host_info += "=============================\n"
            host_info += "name: " + interface.name() + "\n"
            host_info += QNetworkInterface(interface).hardwareAddress() + "\n"
            host_info += str(QNetworkInterface(interface).isValid()) + "\n"
            host_info += "---------\n"
            if QNetworkInterface(interface).flags() & QNetworkInterface.IsUp:
                host_info += "Interface: is up\n"
            if QNetworkInterface(
                    interface).flags() & QNetworkInterface.IsLoopBack:
                host_info += "Interface: is loop back\n"  # 迴環地址
            if QNetworkInterface(
                    interface).flags() & QNetworkInterface.IsRunning:
                host_info += "Interface: is running \n"  # 網絡已經啓動運行
            if interface.flags() & QNetworkInterface.CanMulticast:
                host_info += "Interface: CanMulticast\n"  # 多播
            if interface.flags() & QNetworkInterface.CanBroadcast:
                host_info += "Interface: CanBroadcast\n"
            host_info += "---------\n"

            entryList = QNetworkInterface(interface).addressEntries()
            for entry in entryList:
                address = entry.ip()
                if QHostAddress(address).protocol(
                ) == QAbstractSocket.IPv4Protocol:  # and  \
                    # str(address.toString()) != "127.0.0.1":
                    host_info += "IP Address: " + QNetworkAddressEntry(
                        entry).ip().toString() + "\n"
                    host_info += "Netmask: " + QNetworkAddressEntry(
                        entry).netmask().toString() + "\n"
                    host_info += "Broadcast: " + QNetworkAddressEntry(
                        entry).broadcast().toString() + "\n"
            host_info += "=============================\n"
        self.sig.emit(host_info)
예제 #5
0
 def host_to_addr(host: str) -> QHostAddress:
     """Get the IPv4 address of a given hostname.
     It is required to use this method in order to get the actual IP
     as it turns out that QHostAddress(host) does not do any DNS lookup.
     """
     host_info = QHostInfo.fromName(host)
     for address in host_info.addresses():
         if address.protocol() == QAbstractSocket.IPv4Protocol:
             return address
예제 #6
0
    def run(self):
        #       获取IP
        socket = MyTcpsocket()
        socket.sign_recv.connect(self.sign_thread_recv)
        self.sign_thread_send.connect(socket.sign_send)

        hostname = QHostInfo.localHostName()
        info = QHostInfo.fromName(hostname)
        self.sign_thread_start.emit(info.addresses()[0].toString())
        self.exec_()
예제 #7
0
 def getLocalIpList():
     """
     返回本地网卡的ip列表
     :return: strlist
     """
     myHostInfo = QHostInfo.fromName(QHostInfo.localHostName())
     ipv4_addrs = list(
         filter(
             lambda myaddr: myaddr.protocol() == QAbstractSocket.
             IPv4Protocol, myHostInfo.addresses()))
     ipv4_straddrs = list(map(lambda myaddr: myaddr.toString(), ipv4_addrs))
     return ipv4_straddrs
예제 #8
0
파일: pac.py 프로젝트: phansch/qutebrowser
    def dnsResolve(self, host):
        """Resolve a DNS hostname.

        Resolves the given DNS hostname into an IP address, and returns it
        in the dot-separated format as a string.

        Args:
            host: hostname to resolve.
        """
        ips = QHostInfo.fromName(host)
        if ips.error() != QHostInfo.NoError or not ips.addresses():
            err_f = "Failed to resolve host during PAC evaluation: {}"
            log.network.info(err_f.format(host))
            return QJSValue(QJSValue.NullValue)
        else:
            return ips.addresses()[0].toString()
예제 #9
0
    def dnsResolve(self, host):
        """Resolve a DNS hostname.

        Resolves the given DNS hostname into an IP address, and returns it
        in the dot-separated format as a string.

        Args:
            host: hostname to resolve.
        """
        ips = QHostInfo.fromName(host)
        if ips.error() != QHostInfo.NoError or not ips.addresses():
            err_f = "Failed to resolve host during PAC evaluation: {}"
            log.network.info(err_f.format(host))
            return QJSValue(QJSValue.NullValue)
        else:
            return ips.addresses()[0].toString()
예제 #10
0
def _is_url_dns(url):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as QUrl, ideally via qurl_from_user_input.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    if not url.isValid():
        return False
    host = url.host()
    log.url.debug("DNS request for {}".format(host))
    if not host:
        return False
    info = QHostInfo.fromName(host)
    return not info.error()
예제 #11
0
def _is_url_dns(url):
    """Check if a URL is really a URL via DNS.

    Args:
        url: The URL to check for as QUrl, ideally via qurl_from_user_input.

    Return:
        True if the URL really is a URL, False otherwise.
    """
    if not url.isValid():
        return False
    host = url.host()
    log.url.debug("DNS request for {}".format(host))
    if not host:
        return False
    info = QHostInfo.fromName(host)
    return not info.error()
예제 #12
0
    def __processReadyRead(self):
        """
        Private slot to handle the readyRead signal.
        """
        if self.__state == Connection.WaitingForGreeting:
            if not self.__readProtocolHeader():
                return
            if self.__currentDataType != Connection.Greeting:
                self.abort()
                return
            self.__state = Connection.ReadingGreeting

        if self.__state == Connection.ReadingGreeting:
            if not self.__hasEnoughData():
                return

            self.__buffer = QByteArray(
                self.read(self.__numBytesForCurrentDataType))
            if self.__buffer.size() != self.__numBytesForCurrentDataType:
                self.abort()
                return

            try:
                user, serverPort = \
                    str(self.__buffer, encoding="utf-8").split(":")
            except ValueError:
                self.abort()
                return
            self.__serverPort = int(serverPort)

            hostInfo = QHostInfo.fromName(self.peerAddress().toString())
            self.__username = "******".format(user, hostInfo.hostName(),
                                                   self.peerPort())
            self.__currentDataType = Connection.Undefined
            self.__numBytesForCurrentDataType = 0
            self.__buffer.clear()

            if not self.isValid():
                self.abort()
                return

            bannedName = "{0}@{1}".format(
                user,
                hostInfo.hostName(),
            )
            Preferences.syncPreferences()
            if bannedName in Preferences.getCooperation("BannedUsers"):
                self.rejected.emit(
                    self.tr("* Connection attempted by banned user '{0}'.").
                    format(bannedName))
                self.abort()
                return

            if self.__serverPort != self.peerPort() and \
               not Preferences.getCooperation("AutoAcceptConnections"):
                # don't ask for reverse connections or
                # if we shall accept automatically
                res = E5MessageBox.yesNo(
                    None,
                    self.tr("New Connection"),
                    self.tr("""<p>Accept connection from """
                            """<strong>{0}@{1}</strong>?</p>""").format(
                                user, hostInfo.hostName()),
                    yesDefault=True)
                if not res:
                    self.abort()
                    return

            if self.__client is not None:
                chatWidget = self.__client.chatWidget()
                if chatWidget is not None and not chatWidget.isVisible():
                    e5App().getObject(
                        "UserInterface").activateCooperationViewer()

            if not self.__isGreetingMessageSent:
                self.__sendGreetingMessage()

            self.__pingTimer.start()
            self.__pongTime.start()
            self.__state = Connection.ReadyForUse
            self.readyForUse.emit()

        while self.bytesAvailable():
            if self.__currentDataType == Connection.Undefined:
                if not self.__readProtocolHeader():
                    return

            if not self.__hasEnoughData():
                return

            self.__processData()
예제 #13
0
    def __processReadyRead(self):
        """
        Private slot to handle the readyRead signal.
        """
        if self.__state == Connection.WaitingForGreeting:
            if not self.__readProtocolHeader():
                return
            if self.__currentDataType != Connection.Greeting:
                self.abort()
                return
            self.__state = Connection.ReadingGreeting
        
        if self.__state == Connection.ReadingGreeting:
            if not self.__hasEnoughData():
                return
            
            self.__buffer = QByteArray(
                self.read(self.__numBytesForCurrentDataType))
            if self.__buffer.size() != self.__numBytesForCurrentDataType:
                self.abort()
                return
            
            try:
                user, serverPort = \
                    str(self.__buffer, encoding="utf-8").split(":")
            except ValueError:
                self.abort()
                return
            self.__serverPort = int(serverPort)
            
            hostInfo = QHostInfo.fromName(self.peerAddress().toString())
            self.__username = "******".format(
                user,
                hostInfo.hostName(),
                self.peerPort()
            )
            self.__currentDataType = Connection.Undefined
            self.__numBytesForCurrentDataType = 0
            self.__buffer.clear()
            
            if not self.isValid():
                self.abort()
                return
            
            bannedName = "{0}@{1}".format(
                user,
                hostInfo.hostName(),
            )
            Preferences.syncPreferences()
            if bannedName in Preferences.getCooperation("BannedUsers"):
                self.rejected.emit(self.tr(
                    "* Connection attempted by banned user '{0}'.")
                    .format(bannedName))
                self.abort()
                return
            
            if self.__serverPort != self.peerPort() and \
               not Preferences.getCooperation("AutoAcceptConnections"):
                # don't ask for reverse connections or
                # if we shall accept automatically
                res = E5MessageBox.yesNo(
                    None,
                    self.tr("New Connection"),
                    self.tr("""<p>Accept connection from """
                            """<strong>{0}@{1}</strong>?</p>""").format(
                        user, hostInfo.hostName()),
                    yesDefault=True)
                if not res:
                    self.abort()
                    return

            if self.__client is not None:
                chatWidget = self.__client.chatWidget()
                if chatWidget is not None and not chatWidget.isVisible():
                    e5App().getObject(
                        "UserInterface").activateCooperationViewer()
            
            if not self.__isGreetingMessageSent:
                self.__sendGreetingMessage()
            
            self.__pingTimer.start()
            self.__pongTime.start()
            self.__state = Connection.ReadyForUse
            self.readyForUse.emit()
        
        while self.bytesAvailable():
            if self.__currentDataType == Connection.Undefined:
                if not self.__readProtocolHeader():
                    return
            
            if not self.__hasEnoughData():
                return
            
            self.__processData()