Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Setting Address in QHostAddress



  • I'm creating a simple object to send UDP packets to statsd. I'm getting a segsegv on the writeDataGram line.

    #include <qsettings.h>
    #include <QDebug>
    #include <QtNetwork/QHostAddress>
    #include "statsd.h"
    
    Statsd::Statsd(QObject *parent) : QObject(parent)
    {
        setSocketValues("SomeUnusedOrg", "ToForceDefaults");
        qDebug() << "Statsd target set to -- port: " << _targetPort <<  " IP: " << _targetIP << endl;
    }
    
    Statsd::Statsd(QByteArray organization, QByteArray application, QObject *parent) : QObject(parent)
    {
        setSocketValues(organization, application);
        _socket = new QUdpSocket(this);
        _socket->bind(QHostAddress::LocalHost, _bindPort);
        qDebug() << "Statsd target set to -- port: " << _targetPort <<  " IP: " << _targetIP << endl;
    }
    
    Statsd::~Statsd()
    {
        if (_socket != nullptr)
            _socket->deleteLater();
    
    }
    
    void Statsd::setSocketValues(QByteArray organization, QByteArray application) {
        QSettings qs(organization, application);
        _targetPort = qs.value("statsdport", 8125).toUInt();
        _targetIP = qs.value("statsdip", "127.0.0.1").toByteArray();
        _bindPort = qs.value("statsdbindport", 2000).toUInt();
    }
    
    qint64 Statsd::sendUDP(QByteArray &data)
    {
        QHostAddress address;
        qint64 rv;
        if (address.setAddress(_targetIP.data()))
          #segsegv on the next line.
          rv = _socket->writeDatagram(data.data(), data.length(), address, _targetPort);
        else {
          qWarning() << "Error sending statsd udp packet" << endl;
          rv=-1;
        }
        return rv;
    }
    
    

    Do you see what might be wrong with this?
    I'm using 127.0.0.1 as the address to use. I realize that there is a QHostAddress::LocalHost, but I want to write this generically so any IPv4 address would work.



  • the constructor with signature Statsd::Statsd(QObject*) does not allocate _socket so it's likely it's a dangling pointer causing sigsev



  • Doh! That was it. Too much time looking at the code I couldn't see it. Thanks.


Log in to reply