00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030 #include <QtDebug>
00031 #include <QIODevice>
00032 #include <QTcpSocket>
00033 #include "brisanetwork.h"
00034
00035 QBool isLoopbackIPv4Address(QString address) {
00036 return QBool(!address.compare("127.0.0.1"));
00037 }
00038
00039 QBool isLoopbackIPv6Address(QString address) {
00040 return QBool(!address.compare("0:0:0:0:0:0:0:1"));
00041 }
00042
00043 QBool isPromiscuousIPv4Address(QString address) {
00044 return QBool(!address.compare("0.0.0.0"));
00045 }
00046
00047 QBool isPromiscuousIPv6Address(QString address) {
00048 return QBool(!address.compare("0:0:0:0:0:0:0:0") | !address.compare("::"));
00049 }
00050
00051 QString getValidIP() {
00052 foreach(QHostAddress addressEntry , QNetworkInterface::allAddresses() )
00053 {
00054 QString address = addressEntry.toString();
00055 if (!(isLoopbackIPv4Address(address)) && !(isLoopbackIPv6Address(
00056 address)) && !(isPromiscuousIPv4Address(address))
00057 && !(isPromiscuousIPv6Address(address))) {
00058 return address;
00059 }
00060 }
00061 qDebug()
00062 << "Couldn't acquire a non loopback IP address,returning 127.0.0.1.";
00063
00064
00065 return "127.0.0.1";
00066 }
00067
00068
00069 QString getIp(QString networkInterface) {
00070 foreach( QNetworkInterface interface, QNetworkInterface::allInterfaces() )
00071 {
00072 foreach( QNetworkAddressEntry addressEntry, interface.addressEntries() )
00073 {
00074 if (interface.name() == networkInterface)
00075 return QHostAddress(addressEntry.ip()).toString();
00076 }
00077 }
00078 return "";
00079 }
00080
00081 QBool isPortOpen(QString address, qint16 port, qint16 timeout) {
00082 QTcpSocket *socket = new QTcpSocket();
00083 socket->connectToHost(address, port);
00084 socket->waitForConnected(timeout);
00085 switch (socket->state()) {
00086 case QAbstractSocket::UnconnectedState:
00087 return QBool(false);
00088 delete socket;
00089 break;
00090
00091 case QAbstractSocket::ConnectingState:
00092
00093 socket->waitForConnected(timeout);
00094 if (socket->state() == QAbstractSocket::ConnectedState) {
00095 return QBool(true);
00096 } else {
00097 return QBool(false);
00098 }
00099 delete socket;
00100 break;
00101
00102 case QAbstractSocket::ConnectedState:
00103 return QBool(true);
00104 delete socket;
00105 break;
00106 default:
00107 delete socket;
00108 break;
00109 }
00110 delete socket;
00111 return QBool(false);
00112 }
00113
00114 quint16 getPort() {
00115 srand( time(NULL));
00116
00117
00118 quint16 randomPort =
00119 (49152 + rand()/ (RAND_MAX / (65535 - 49152 + 1) + 1));
00120 qDebug() << "Port value chosen:" << randomPort;
00121 while (isPortOpen(getValidIP(), randomPort, 5)) {
00122 qDebug() << "Port is already opened, trying another ";
00123 randomPort = (49152 + rand() / (RAND_MAX / (65535 - 49152 + 1) + 1));
00124 }
00125 return randomPort;
00126 }
00127