Search code examples
c++qtqtcoreqtnetwork

Qt ASCII to IP function


I'm attempting my hand at creating a UDP terminal (custom) using Qt - Does anyone know if there's a widget or class for handling the conversion of the IP address from ASCII to numeric (hex) or do I have to write that myself? Basically "192.168.1.1" -> "0xC0A80101". I'm not opposed to writing it, just want to know if anyone knows if it already exists. Tried searching, not much luck. Thanks all


Solution

  • The key class here is QHostAddress as follows:

    main.cpp

    #include <QHostAddress>
    
    #include <QTextStream>
    #include <QString>
    
    int main()
    {
        QTextStream standardOutput(stdout);
        // You could use this, too:
        // standardOutput.setIntegerBase(16);
        // standardOutPut.setNumberFlags(QTextStream::ShowBase);
        quint32 ipAddress = QHostAddress("192.168.1.1").toIPv4Address();
        QString hexIpAddress = QString::number(ipAddress, 16);
        QString prefixedUppercaseHexIpAddress = QString("0x%1")
                                                .arg(uppercaseHexIpAddress);
        standardOutput << prefixedUppercaseHexIpAddress;
        return 0;
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT = core network
    SOURCES += main.cpp
    

    Build and Run

    qmake && make && ./main
    

    Output

    0xC0A80101