Exemple #1
0
    def get_alldevices(self):
        dv = QNetworkInterface.allInterfaces()
        # nan = [interface.addressEntries() for interface
        #        in dv]
        availabledevices = {
            interface.humanReadableName():
            interface.addressEntries()[i].ip().toString()
            for interface in dv for i in range(len(interface.addressEntries()))
            if (len(interface.addressEntries())
                and not interface.addressEntries()[i].ip().isLinkLocal() and
                interface.addressEntries()[i].ip().toString() != "127.0.0.1"
                and ":" not in interface.addressEntries()[i].ip().toString()
                and "." in interface.addressEntries()[i].ip().toString())
        }

        self.devicedict = {
            k: v
            for k, v in sorted(availabledevices.items(),
                               key=lambda item: item[1],
                               reverse=True)
        }
        # if len(self.devicedict)==0:
        #     self.showm_signal.emit("未接入网络!")
        print(self.devicedict)
        return self.devicedict
Exemple #2
0
    def sessionOpened(self):
        if self.networkSession is not None:
            config = self.networkSession.configuration()

            if config.type() == QNetworkConfiguration.UserChoice:
                id = self.networkSession.sessionProperty('UserChoiceConfiguration')
            else:
                id = config.identifier()

            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            settings.setValue('DefaultNetworkConfiguration', id)
            settings.endGroup();

        self.tcpServer = QTcpServer(self)
        if not self.tcpServer.listen():
            QMessageBox.critical(self, "Fortune Server",
                    "Unable to start the server: %s." % self.tcpServer.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.statusLabel.setText("The server is running on\n\nIP: %s\nport %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.tcpServer.serverPort()))
 def getIP(self):
     localhost = QHostAddress(QHostAddress.LocalHost)
     addresses = QNetworkInterface().allAddresses()
     if addresses:
         for address in addresses:
             if address.protocol() == QAbstractSocket.IPv4Protocol and address != localhost:
                 return address.toString()
def getIPAddress():
    for ipAddress in QNetworkInterface.allAddresses():
        if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address(
        ) != 0:
            break
    else:
        ipAddress = QHostAddress(QHostAddress.LocalHost)
    return ipAddress.toString()
Exemple #5
0
 def load_all(self):
     for i in QNetworkInterface.allInterfaces():
         for e in i.addressEntries():
             if e.ip().isLoopback() == False and i.isValid() and e.ip(
             ).isMulticast() == False and e.ip().isNull() == False and e.ip(
             ).protocol() == QAbstractSocket.IPv4Protocol and e.ip(
             ).isLinkLocal() == False:
                 self.append(Interface(self.mem).init__create(i, e))
    def __init__(self, parent=None):
        super(BlockingClient, self).__init__(parent)

        self.thread = FortuneThread()
        self.currentFortune = ""

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address(
            ) != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.hostLineEdit = QLineEdit(ipAddress)
        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostLineEdit)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel(
            "This example requires that you run the Fortune Server example as well."
        )
        self.statusLabel.setWordWrap(True)

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.thread.newFortune.connect(self.showFortune)
        self.thread.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostLineEdit, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Blocking Fortune Client")
        self.portLineEdit.setFocus()
Exemple #7
0
    def getIfcAddress(self, ifc):
        myIfc = QNetworkInterface.interfaceFromName(ifc)
        addrList = myIfc.addressEntries()

        for addr in addrList:
            if addr.ip().protocol() == QAbstractSocket.IPv4Protocol:
                return addr.ip()

        return QHostAddress()
Exemple #8
0
    def fillActivateIps(self):
        print("start fill")
        for interface in QNetworkInterface.allInterfaces():
            iflags = interface.flags()
            if (iflags & QNetworkInterface.IsRunning) and  not (iflags  & QNetworkInterface.IsLoopBack) :
                for addrentry in interface.addressEntries():
#                    print("append ",addrentry.ip().toString(),addrentry.ip().protocol())
                    if addrentry.ip().protocol() == QAbstractSocket.IPv4Protocol:
                        self.plainTextEdit_iplist.appendPlainText("{}:{}".format(addrentry.ip().toString(), self.port))
Exemple #9
0
def isConnectedToNetwork(reference=None):
    ifaces = QNetworkInterface.allInterfaces()
    result = False
    for iface in ifaces:
        if (iface.flags() & QNetworkInterface.IsUp) and not (iface.flags() & QNetworkInterface.IsLoopBack):
            for entry in iface.addressEntries():
                result = True
                break
    return result
    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)
Exemple #11
0
def get_local_ip4():
    """
    Creates a dictionary of local IPv4 interfaces on local machine.
    If no active interfaces available, returns a dict of localhost IPv4 information

    :returns: Dict of interfaces
    """
    # Get the local IPv4 active address(es) that are NOT localhost (lo or '127.0.0.1')
    log.debug('Getting local IPv4 interface(es) information')
    my_ip4 = {}
    for iface in QNetworkInterface.allInterfaces():
        log.debug('Checking for isValid and flags == IsUP | IsRunning')
        if not iface.isValid() or not (
                iface.flags() &
            (QNetworkInterface.IsUp | QNetworkInterface.IsRunning)):
            continue
        log.debug('Checking address(es) protocol')
        for address in iface.addressEntries():
            ip = address.ip()
            # NOTE: Next line will skip if interface is localhost - keep for now until we decide about it later
            # if (ip.protocol() == QAbstractSocket.IPv4Protocol) and (ip != QHostAddress.LocalHost):
            log.debug('Checking for protocol == IPv4Protocol')
            if ip.protocol() == QAbstractSocket.IPv4Protocol:
                log.debug('Getting interface information')
                my_ip4[iface.name()] = {
                    'ip':
                    ip.toString(),
                    'broadcast':
                    address.broadcast().toString(),
                    'netmask':
                    address.netmask().toString(),
                    'prefix':
                    address.prefixLength(),
                    'localnet':
                    QHostAddress(address.netmask().toIPv4Address()
                                 & ip.toIPv4Address()).toString()
                }
                log.debug(
                    'Adding {iface} to active list'.format(iface=iface.name()))
    if 'localhost' in my_ip4:
        log.debug('Renaming windows localhost to lo')
        my_ip4['lo'] = my_ip4['localhost']
        my_ip4.pop('localhost')
    if len(my_ip4) == 0:
        log.warning('No active IPv4 network interfaces detected')
    if len(my_ip4) == 1:
        if 'lo' in my_ip4:
            # No active interfaces - so leave localhost in there
            log.warning('No active IPv4 interfaces found except localhost')
    else:
        # Since we have a valid IP4 interface, remove localhost
        if 'lo' in my_ip4:
            log.debug('Found at least one IPv4 interface, removing localhost')
            my_ip4.pop('lo')

    return my_ip4
    def __init__(self, parent=None):
        super(BlockingClient, self).__init__(parent)

        self.thread = FortuneThread()
        self.currentFortune = ''

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.hostLineEdit = QLineEdit(ipAddress)
        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostLineEdit)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel(
                "This example requires that you run the Fortune Server example as well.")
        self.statusLabel.setWordWrap(True)

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.thread.newFortune.connect(self.showFortune)
        self.thread.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostLineEdit, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Blocking Fortune Client")
        self.portLineEdit.setFocus()
Exemple #13
0
def isConnectedToNetwork(reference=None):
    ifaces = QNetworkInterface.allInterfaces()
    result = False
    for iface in ifaces:
        if (iface.flags() & QNetworkInterface.IsUp
            ) and not (iface.flags() & QNetworkInterface.IsLoopBack):
            for entry in iface.addressEntries():
                result = True
                break
    return result
Exemple #14
0
def getAllAddresses():
    addresses = QNetworkInterface.allAddresses()
    required = []
    for address in addresses:
        if (address.protocol() == QAbstractSocket.IPv4Protocol) and \
            (address != QHostAddress(QHostAddress.LocalHost)):
            if address.toString().startswith(
                    '169'):  # to avoid link-local addresses
                required.append(address.toString())
    return required
Exemple #15
0
    def displayAllHostaddresses(self):
        v4addrs = list()
        v6addrs = list()
        for address in QNetworkInterface().allAddresses():
            if address.protocol() == 0:
                v4addrs.append(address.toString())
            # if address.protocol() == 1:
            #    v6addrs.append(address.toString())

        self.setCurrentSongText(", ".join(["%s" % addr for addr in v4addrs]))
        self.setNewsText(", ".join(["%s" % (addr) for addr in v6addrs]))
Exemple #16
0
    def display_all_hostaddresses(self):
        v4addrs = list()
        v6addrs = list()
        for address in QNetworkInterface().allAddresses():
            if address.protocol() == 0:
                v4addrs.append(address.toString())
            # if address.protocol() == 1:
            #    v6addrs.append(address.toString())

        self.set_current_song_text(", ".join(["%s" % addr for addr in v4addrs]))
        self.set_news_text(", ".join(["%s" % addr for addr in v6addrs]))
Exemple #17
0
 def getIP(self):
     """
     获得用户IP
     """
     addressList = QNetworkInterface.allAddresses()
     for address in addressList:
         if address.protocol(
         ) == QAbstractSocket.IPv4Protocol and address != QHostAddress.LocalHost and address.toString(
         )[:3] != "169" and address.toString().split(".")[-1] != "1":
             return address.toString()
     return "0.0.0.0"
Exemple #18
0
 def _available_server_ipv4_addresses(self):
     from PyQt5.QtNetwork import QNetworkInterface, QAbstractSocket
     a = []
     for ni in QNetworkInterface.allInterfaces():
         flags = ni.flags()
         if (flags & QNetworkInterface.IsUp
             ) and not (flags & QNetworkInterface.IsLoopBack):
             for ae in ni.addressEntries():
                 ha = ae.ip()
                 if (ha.protocol() == QAbstractSocket.IPv4Protocol
                         and not ha.isLoopback() and not ha.isNull()
                         and not ha.toString().startswith('169.254')
                     ):  # Exclude link-local addresses
                     a.append(ha)
     return a
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent object (QObject)
        """
        super(CooperationClient, self).__init__(parent)

        self.__chatWidget = parent

        self.__servers = []
        for networkInterface in QNetworkInterface.allInterfaces():
            for addressEntry in networkInterface.addressEntries():
                address = addressEntry.ip()
                # fix scope of link local addresses
                if address.toString().lower().startswith("fe80"):
                    address.setScopeId(networkInterface.humanReadableName())
                server = CooperationServer(address, self)
                server.newConnection.connect(self.__newConnection)
                self.__servers.append(server)

        self.__peers = collections.defaultdict(list)

        self.__initialConnection = None

        envVariables = [
            "USERNAME.*", "USER.*", "USERDOMAIN.*", "HOSTNAME.*",
            "DOMAINNAME.*"
        ]
        environment = QProcess.systemEnvironment()
        found = False
        for envVariable in envVariables:
            for env in environment:
                if QRegExp(envVariable).exactMatch(env):
                    envList = env.split("=")
                    if len(envList) == 2:
                        self.__username = envList[1].strip()
                        found = True
                        break

            if found:
                break

        if self.__username == "":
            self.__username = self.tr("unknown")

        self.__listening = False
        self.__serversErrorString = ""
Exemple #20
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent object (QObject)
     """
     super(CooperationClient, self).__init__(parent)
     
     self.__chatWidget = parent
     
     self.__servers = []
     for networkInterface in QNetworkInterface.allInterfaces():
         for addressEntry in networkInterface.addressEntries():
             address = addressEntry.ip()
             # fix scope of link local addresses
             if address.toString().lower().startswith("fe80"):
                 address.setScopeId(networkInterface.humanReadableName())
             server = CooperationServer(address, self)
             server.newConnection.connect(self.__newConnection)
             self.__servers.append(server)
     
     self.__peers = collections.defaultdict(list)
     
     self.__initialConnection = None
     
     envVariables = ["USERNAME.*", "USER.*", "USERDOMAIN.*",
                     "HOSTNAME.*", "DOMAINNAME.*"]
     environment = QProcess.systemEnvironment()
     found = False
     for envVariable in envVariables:
         for env in environment:
             if QRegExp(envVariable).exactMatch(env):
                 envList = env.split("=")
                 if len(envList) == 2:
                     self.__username = envList[1].strip()
                     found = True
                     break
         
         if found:
             break
     
     if self.__username == "":
         self.__username = self.tr("unknown")
     
     self.__listening = False
     self.__serversErrorString = ""
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(
                self,
                "Threaded Fortune Server",
                "Unable to start the server: %s." % self.server.errorString(),
            )
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText(
            "The server is running on\n\nIP: %s\nport: %d\n\n"
            "Run the Fortune Client example now."
            % (ipAddress, self.server.serverPort())
        )

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
Exemple #22
0
def get_network_interfaces():
    """
    Creates a dictionary of local IPv4 interfaces on local machine.
    If no active interfaces available, returns a dict of localhost IPv4 information

    :returns: Dict of interfaces
    """
    log.debug('Getting local IPv4 interface(es) information')
    interfaces = {}
    for interface in QNetworkInterface.allInterfaces():
        interface_name = interface.name()
        if INTERFACE_FILTER.search(interface_name):
            log.debug(
                'Filtering out interfaces we don\'t care about: {name}'.format(
                    name=interface_name))
            continue
        log.debug('Checking for isValid and flags == IsUP | IsRunning')
        if not interface.isValid() or not (
                interface.flags() &
            (QNetworkInterface.IsUp | QNetworkInterface.IsRunning)):
            continue
        log.debug('Checking address(es) protocol')
        for address in interface.addressEntries():
            ip = address.ip()
            log.debug('Checking for protocol == IPv4Protocol')
            if ip.protocol() == QAbstractSocket.IPv4Protocol:
                log.debug('Getting interface information')
                interfaces[interface_name] = {
                    'ip':
                    ip.toString(),
                    'broadcast':
                    address.broadcast().toString(),
                    'netmask':
                    address.netmask().toString(),
                    'prefix':
                    address.prefixLength(),
                    'localnet':
                    QHostAddress(address.netmask().toIPv4Address()
                                 & ip.toIPv4Address()).toString()
                }
                log.debug('Adding {interface} to active list'.format(
                    interface=interface.name()))
    if len(interfaces) == 0:
        log.warning('No active IPv4 network interfaces detected')
    return interfaces
Exemple #23
0
    def getIP(self):
        """
        获得用户IP
        """
        addressList = QNetworkInterface.allAddresses()
        # QNetworkInterface类提供主机的IP地址和网络接口的列表(list类型)。
        # QNetworkInterface表示连接到运行程序的主机的一个网络接口。
        # 每个网络接口可以包含零个或多个IP地址,每个IP地址可选地与网络掩码和/或广播地址相关联。
        # 可以使用addressEntries()获得此类三元组的列表。
        # 当不需要网络掩码或广播地址或其他信息时,使用allAddresses()便捷功能仅获取活动接口的IP地址。

        for address in addressList:
            if address.protocol(
            ) == QAbstractSocket.IPv4Protocol and address != QHostAddress.LocalHost and address.toString(
            )[:3] != "169" and address.toString().split(".")[-1] != "1":
                return address.toString()
            # 只要IPv4、不要169开头的地址、不要结尾是1的IP地址(可能是网关)
        return "0.0.0.0"
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(self, "Threaded Fortune Server",
                    "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
Exemple #25
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.cam = webcam(640, 480, '/dev/video0')
        self.cam.activate()

        self.statusLabel = QLabel()
        self.quitButton = QPushButton("Quit")
        self.quitButton.setAutoDefault(False)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle('Frame Server')

        self.tcpServer = QTcpServer(self)
        self.tcpServer.listen()
        self.client = None

        ipAddress = ''
        for address in QNetworkInterface.allAddresses():
            if address != QHostAddress.LocalHost and address.toIPv4Address():
                ipAddress = address.toString()
                break

        if len(ipAddress) == 0:
            ipAddress = QHostAddress(QHostAddress.LocalHost).toString()

        self.statusLabel.setText(
            'Address:\t\t{}\nPort:\t\t\t{}'.format(ipAddress, self.tcpServer.serverPort()))

        self.quitButton.clicked.connect(self.close)
        self.tcpServer.newConnection.connect(self.clientConnected)
    def sessionOpened(self):
        if self.networkSession is not None:
            config = self.networkSession.configuration()

            if config.type() == QNetworkConfiguration.UserChoice:
                id = self.networkSession.sessionProperty(
                    'UserChoiceConfiguration')
            else:
                id = config.identifier()

            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            settings.setValue('DefaultNetworkConfiguration', id)
            settings.endGroup()

        self.tcpServer = QTcpServer(self)
        if not self.tcpServer.listen():
            QMessageBox.critical(
                self, "Fortune Server", "Unable to start the server: %s." %
                self.tcpServer.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address(
            ) != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        self.statusLabel.setText(
            "The server is running on\n\nIP: %s\nport %d\n\n"
            "Run the Fortune Client example now." %
            (ipAddress, self.tcpServer.serverPort()))
    def __init__(self):
        """
        Constructor
        """
        super(DebuggerGeneralPage, self).__init__()
        self.setupUi(self)
        self.setObjectName("DebuggerGeneralPage")

        t = self.execLineEdit.whatsThis()
        if t:
            t += Utilities.getPercentReplacementHelp()
            self.execLineEdit.setWhatsThis(t)

        try:
            backends = e5App().getObject("DebugServer").getSupportedLanguages()
            for backend in sorted(backends):
                self.passiveDbgBackendCombo.addItem(backend)
        except KeyError:
            self.passiveDbgGroup.setEnabled(False)

        t = self.consoleDbgEdit.whatsThis()
        if t:
            t += Utilities.getPercentReplacementHelp()
            self.consoleDbgEdit.setWhatsThis(t)

        self.consoleDbgCompleter = E5FileCompleter(self.consoleDbgEdit)
        self.dbgTranslationLocalCompleter = E5DirCompleter(
            self.dbgTranslationLocalEdit)

        # set initial values
        interfaces = []
        networkInterfaces = QNetworkInterface.allInterfaces()
        for networkInterface in networkInterfaces:
            addressEntries = networkInterface.addressEntries()
            if len(addressEntries) > 0:
                for addressEntry in addressEntries:
                    if ":" in addressEntry.ip().toString() and \
                            not socket.has_ipv6:
                        continue  # IPv6 not supported by Python
                    interfaces.append("{0} ({1})".format(
                        networkInterface.humanReadableName(),
                        addressEntry.ip().toString()))
        self.interfacesCombo.addItems(interfaces)
        interface = Preferences.getDebugger("NetworkInterface")
        if not socket.has_ipv6:
            # IPv6 not supported by Python
            self.all6InterfacesButton.setEnabled(False)
            if interface == "allv6":
                interface = "all"
        if interface == "all":
            self.allInterfacesButton.setChecked(True)
        elif interface == "allv6":
            self.all6InterfacesButton.setChecked(True)
        else:
            self.selectedInterfaceButton.setChecked(True)
            index = -1
            for i in range(len(interfaces)):
                if QRegExp(".*{0}.*".format(interface))\
                        .exactMatch(interfaces[i]):
                    index = i
                    break
            self.interfacesCombo.setCurrentIndex(index)

        self.allowedHostsList.addItems(Preferences.getDebugger("AllowedHosts"))

        self.remoteCheckBox.setChecked(
            Preferences.getDebugger("RemoteDbgEnabled"))
        self.hostLineEdit.setText(Preferences.getDebugger("RemoteHost"))
        self.execLineEdit.setText(Preferences.getDebugger("RemoteExecution"))

        if self.passiveDbgGroup.isEnabled():
            self.passiveDbgCheckBox.setChecked(
                Preferences.getDebugger("PassiveDbgEnabled"))
            self.passiveDbgPortSpinBox.setValue(
                Preferences.getDebugger("PassiveDbgPort"))
            index = self.passiveDbgBackendCombo.findText(
                Preferences.getDebugger("PassiveDbgType"))
            if index == -1:
                index = 0
            self.passiveDbgBackendCombo.setCurrentIndex(index)

        self.debugEnvironReplaceCheckBox.setChecked(
            Preferences.getDebugger("DebugEnvironmentReplace"))
        self.debugEnvironEdit.setText(
            Preferences.getDebugger("DebugEnvironment"))
        self.automaticResetCheckBox.setChecked(
            Preferences.getDebugger("AutomaticReset"))
        self.debugAutoSaveScriptsCheckBox.setChecked(
            Preferences.getDebugger("Autosave"))
        self.consoleDbgCheckBox.setChecked(
            Preferences.getDebugger("ConsoleDbgEnabled"))
        self.consoleDbgEdit.setText(
            Preferences.getDebugger("ConsoleDbgCommand"))
        self.dbgPathTranslationCheckBox.setChecked(
            Preferences.getDebugger("PathTranslation"))
        self.dbgTranslationRemoteEdit.setText(
            Preferences.getDebugger("PathTranslationRemote"))
        self.dbgTranslationLocalEdit.setText(
            Preferences.getDebugger("PathTranslationLocal"))
        self.debugThreeStateBreakPoint.setChecked(
            Preferences.getDebugger("ThreeStateBreakPoints"))
        self.dontShowClientExitCheckBox.setChecked(
            Preferences.getDebugger("SuppressClientExit"))
        self.exceptionBreakCheckBox.setChecked(
            Preferences.getDebugger("BreakAlways"))
        self.exceptionShellCheckBox.setChecked(
            Preferences.getDebugger("ShowExceptionInShell"))
        self.autoViewSourcecodeCheckBox.setChecked(
            Preferences.getDebugger("AutoViewSourceCode"))
Exemple #28
0
 def __init__(self):
     """
     Constructor
     """
     super(DebuggerGeneralPage, self).__init__()
     self.setupUi(self)
     self.setObjectName("DebuggerGeneralPage")
     
     t = self.execLineEdit.whatsThis()
     if t:
         t += Utilities.getPercentReplacementHelp()
         self.execLineEdit.setWhatsThis(t)
     
     try:
         backends = e5App().getObject("DebugServer").getSupportedLanguages()
         for backend in sorted(backends):
             self.passiveDbgBackendCombo.addItem(backend)
     except KeyError:
         self.passiveDbgGroup.setEnabled(False)
     
     t = self.consoleDbgEdit.whatsThis()
     if t:
         t += Utilities.getPercentReplacementHelp()
         self.consoleDbgEdit.setWhatsThis(t)
     
     self.consoleDbgCompleter = E5FileCompleter(self.consoleDbgEdit)
     self.dbgTranslationLocalCompleter = E5DirCompleter(
         self.dbgTranslationLocalEdit)
     
     # set initial values
     interfaces = []
     networkInterfaces = QNetworkInterface.allInterfaces()
     for networkInterface in networkInterfaces:
         addressEntries = networkInterface.addressEntries()
         if len(addressEntries) > 0:
             for addressEntry in addressEntries:
                 if ":" in addressEntry.ip().toString() and \
                         not socket.has_ipv6:
                     continue    # IPv6 not supported by Python
                 interfaces.append(
                     "{0} ({1})".format(
                         networkInterface.humanReadableName(),
                         addressEntry.ip().toString()))
     self.interfacesCombo.addItems(interfaces)
     interface = Preferences.getDebugger("NetworkInterface")
     if not socket.has_ipv6:
         # IPv6 not supported by Python
         self.all6InterfacesButton.setEnabled(False)
         if interface == "allv6":
             interface = "all"
     if interface == "all":
         self.allInterfacesButton.setChecked(True)
     elif interface == "allv6":
         self.all6InterfacesButton.setChecked(True)
     else:
         self.selectedInterfaceButton.setChecked(True)
         index = -1
         for i in range(len(interfaces)):
             if QRegExp(".*{0}.*".format(interface))\
                     .exactMatch(interfaces[i]):
                 index = i
                 break
         self.interfacesCombo.setCurrentIndex(index)
     
     self.allowedHostsList.addItems(
         Preferences.getDebugger("AllowedHosts"))
     
     self.remoteCheckBox.setChecked(
         Preferences.getDebugger("RemoteDbgEnabled"))
     self.hostLineEdit.setText(
         Preferences.getDebugger("RemoteHost"))
     self.execLineEdit.setText(
         Preferences.getDebugger("RemoteExecution"))
     
     if self.passiveDbgGroup.isEnabled():
         self.passiveDbgCheckBox.setChecked(
             Preferences.getDebugger("PassiveDbgEnabled"))
         self.passiveDbgPortSpinBox.setValue(
             Preferences.getDebugger("PassiveDbgPort"))
         index = self.passiveDbgBackendCombo.findText(
             Preferences.getDebugger("PassiveDbgType"))
         if index == -1:
             index = 0
         self.passiveDbgBackendCombo.setCurrentIndex(index)
     
     self.debugEnvironReplaceCheckBox.setChecked(
         Preferences.getDebugger("DebugEnvironmentReplace"))
     self.debugEnvironEdit.setText(
         Preferences.getDebugger("DebugEnvironment"))
     self.automaticResetCheckBox.setChecked(
         Preferences.getDebugger("AutomaticReset"))
     self.debugAutoSaveScriptsCheckBox.setChecked(
         Preferences.getDebugger("Autosave"))
     self.consoleDbgCheckBox.setChecked(
         Preferences.getDebugger("ConsoleDbgEnabled"))
     self.consoleDbgEdit.setText(
         Preferences.getDebugger("ConsoleDbgCommand"))
     self.dbgPathTranslationCheckBox.setChecked(
         Preferences.getDebugger("PathTranslation"))
     self.dbgTranslationRemoteEdit.setText(
         Preferences.getDebugger("PathTranslationRemote"))
     self.dbgTranslationLocalEdit.setText(
         Preferences.getDebugger("PathTranslationLocal"))
     self.debugThreeStateBreakPoint.setChecked(
         Preferences.getDebugger("ThreeStateBreakPoints"))
     self.dontShowClientExitCheckBox.setChecked(
         Preferences.getDebugger("SuppressClientExit"))
     self.exceptionBreakCheckBox.setChecked(
         Preferences.getDebugger("BreakAlways"))
     self.exceptionShellCheckBox.setChecked(
         Preferences.getDebugger("ShowExceptionInShell"))
     self.autoViewSourcecodeCheckBox.setChecked(
         Preferences.getDebugger("AutoViewSourceCode"))
 def getIP(self):
     info = QNetworkInterface().allAddresses()
     print(info[3].toString())
     if info:
         return info[3].toString()
Exemple #30
0
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.networkSession = None
        self.blockSize = 0
        self.currentFortune = ''

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        self.hostCombo = QComboBox()
        self.hostCombo.setEditable(True)

        name = QHostInfo.localHostName()
        if name != '':
            self.hostCombo.addItem(name)

            domain = QHostInfo.localDomainName()
            if domain != '':
                self.hostCombo.addItem(name + '.' + domain)

        if name != 'localhost':
            self.hostCombo.addItem('localhost')

        ipAddressesList = QNetworkInterface.allAddresses()

        for ipAddress in ipAddressesList:
            if not ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        for ipAddress in ipAddressesList:
            if ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostCombo)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel("This examples requires that you run "
                                  "the Fortune Server example as well.")

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.tcpSocket = QTcpSocket(self)

        self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.tcpSocket.readyRead.connect(self.readFortune)
        self.tcpSocket.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostCombo, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Fortune Client")
        self.portLineEdit.setFocus()

        manager = QNetworkConfigurationManager()
        if manager.capabilities(
        ) & QNetworkConfigurationManager.NetworkSessionRequired:
            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            id = settings.value('DefaultNetworkConfiguration')
            settings.endGroup()

            config = manager.configurationFromIdentifier(id)
            if config.state() & QNetworkConfiguration.Discovered == 0:
                config = manager.defaultConfiguration()

            self.networkSession = QNetworkSession(config, self)
            self.networkSession.opened.connect(self.sessionOpened)

            self.getFortuneButton.setEnabled(False)
            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.networkSession = None
        self.blockSize = 0
        self.currentFortune = ''
        self.title = "扫码收货PC辅助程序"

        hostLabel = QLabel('IP:')
        hostLabel.setFont(qtawesome.font('fa', 14))

        portLabel = QLabel('端口:')
        portLabel.setFont(qtawesome.font('fa', 14))

        taskCodeLabel = QLabel('任务码:')
        taskCodeLabel.setFont(qtawesome.font('fa', 14))
        self.serverMsgLable = QLabel('来自服务端的消息:')
        self.serverMsgLable.setFont(qtawesome.font('fa', 14))

        self.sendMsgLabel = QLabel('将要发送的消息:')
        self.sendMsgLabel.setFont(qtawesome.font('fa', 14))

        self.hostCombo = QComboBox()
        self.hostCombo.setEditable(True)

        name = QHostInfo.localHostName()
        if name != '':
            self.hostCombo.addItem(name)

            domain = QHostInfo.localDomainName()
            if domain != '':
                self.hostCombo.addItem(name + '.' + domain)

        if name != 'localhost':
            self.hostCombo.addItem('10.286.88.124')

        ipAddressesList = QNetworkInterface.allAddresses()

        for ipAddress in ipAddressesList:
            if not ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        for ipAddress in ipAddressesList:
            if ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))
        self.portLineEdit.setPlaceholderText("请输入端口")

        self.taskLineEdit = QLineEdit()
        self.taskLineEdit.setPlaceholderText("请向组长询问后输入任务码")
        self.taskLineEdit.setValidator(QIntValidator(1, 9999, self))

        self.serverLineEdit = QLineEdit()
        self.serverLineEdit.setPlaceholderText('服务器发送的消息会显示在这里')

        self.sendTextEdit = QTextEdit()
        self.sendTextEdit.setPlaceholderText('请输入先要发送给服务器的消息')

        hostLabel.setBuddy(self.hostCombo)
        portLabel.setBuddy(self.portLineEdit)
        taskCodeLabel.setBuddy(self.taskLineEdit)
        self.serverMsgLable.setBuddy(self.serverLineEdit)
        self.sendMsgLabel.setBuddy(self.sendTextEdit)

        self.statusLabel = QLabel("状态:尚未连接")
        self.statusLabel.setAutoFillBackground(True)
        self.statusLabel.setAlignment(Qt.AlignCenter)
        palette = QPalette()  # 新建一个调色板
        palette.setColor(QPalette.Window, Qt.red)  # 设置颜色
        self.statusLabel.setPalette(palette)
        self.statusLabel.setStyleSheet('''
                color:#ffffff;
                font-size:18px;
                font-weight:bold;
        ''')

        self.getFortuneButton = QPushButton("启动连接")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("退出")
        self.stopButton = QPushButton("中止连接")
        self.stopButton.setDefault(True)
        self.stopButton.setEnabled(False)

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.stopButton, QDialogButtonBox.AcceptRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)
        self.sendMsgbutton = QPushButton('发送消息')
        self.webSocket = QWebSocket()

        self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.taskLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.CreateNewConn)
        self.stopButton.clicked.connect(self.stopCurrentConn)
        quitButton.clicked.connect(self.close)
        self.webSocket.connected.connect(self.websocketConnect)
        self.webSocket.disconnected.connect(self.webSocketDisconnect)
        self.webSocket.error.connect(self.displayError)
        self.webSocket.textMessageReceived.connect(
            self.webSocketMessageReceived)
        self.sendTextEdit.textChanged.connect(self.enableSendMessageButton)
        self.sendMsgbutton.clicked.connect(self.sendMsgToServer)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostCombo, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(taskCodeLabel, 2, 0)
        mainLayout.addWidget(self.taskLineEdit, 2, 1)
        mainLayout.addWidget(self.statusLabel, 3, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 4, 0, 1, 2)
        mainLayout.addWidget(self.serverMsgLable, 5, 0)
        mainLayout.addWidget(self.serverLineEdit, 5, 1, 1, 1)
        mainLayout.addWidget(self.sendMsgLabel, 6, 0)
        mainLayout.addWidget(self.sendTextEdit, 6, 1)
        mainLayout.addWidget(self.sendMsgbutton, 7, 0, 1, 5)
        self.serverLineEdit.setEnabled(False)
        self.serverMsgLable.setVisible(False)
        self.serverLineEdit.setVisible(False)
        self.sendMsgLabel.setVisible(False)
        self.sendTextEdit.setVisible(False)
        self.sendMsgbutton.setEnabled(False)
        self.sendMsgbutton.setVisible(False)
        self.setLayout(mainLayout)
        mainLayout.setSpacing(10)
        self.setWindowTitle(self.title)
        self.portLineEdit.setFocus()
        manager = QNetworkConfigurationManager()
        if manager.capabilities(
        ) & QNetworkConfigurationManager.NetworkSessionRequired:
            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            id = settings.value('DefaultNetworkConfiguration')
            settings.endGroup()

            config = manager.configurationFromIdentifier(id)
            if config.state() & QNetworkConfiguration.Discovered == 0:
                config = manager.defaultConfiguration()

            self.networkSession = QNetworkSession(config, self)
            self.networkSession.opened.connect(self.sessionOpened)

            self.getFortuneButton.setEnabled(False)
            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
Exemple #32
0
    def get_ip(self):
        index_Interface = self.udpSocket_multi.multicastInterface()
        interface_Network = QNetworkInterface.interfaceFromIndex(index_Interface.index())
        own_addr = interface_Network.allAddresses()[0].toString()

        return own_addr
 def get_available_ips(self):
     """Method returning the list of available ips."""
     return QNetworkInterface.allAddresses()
Exemple #34
0
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.networkSession = None
        self.blockSize = 0
        self.currentFortune = ""

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        self.hostCombo = QComboBox()
        self.hostCombo.setEditable(True)

        name = QHostInfo.localHostName()
        if name != "":
            self.hostCombo.addItem(name)

            domain = QHostInfo.localDomainName()
            if domain != "":
                self.hostCombo.addItem(name + "." + domain)

        if name != "localhost":
            self.hostCombo.addItem("localhost")

        ipAddressesList = QNetworkInterface.allAddresses()

        for ipAddress in ipAddressesList:
            if not ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        for ipAddress in ipAddressesList:
            if ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostCombo)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.")

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.tcpSocket = QTcpSocket(self)

        self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.tcpSocket.readyRead.connect(self.readFortune)
        self.tcpSocket.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostCombo, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Fortune Client")
        self.portLineEdit.setFocus()

        manager = QNetworkConfigurationManager()
        if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired:
            settings = QSettings(QSettings.UserScope, "QtProject")
            settings.beginGroup("QtNetwork")
            id = settings.value("DefaultNetworkConfiguration")
            settings.endGroup()

            config = manager.configurationFromIdentifier(id)
            if config.state() & QNetworkConfiguration.Discovered == 0:
                config = manager.defaultConfiguration()

            self.networkSession = QNetworkSession(config, self)
            self.networkSession.opened.connect(self.sessionOpened)

            self.getFortuneButton.setEnabled(False)
            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
Exemple #35
0
def get_host_ip(lh=False):
    if lh:
        return '127.0.1.1'
    address = QNetworkInterface.allAddresses()
    ip = address[2].toString()
    return ip