From ccec50e18e0286edc69ee01be3166e688a313dd6 Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Tue, 23 Jul 2019 14:02:01 +0800 Subject: [PATCH] Improve parsing in BitTorrent::PeerAddress::parse --- src/base/bittorrent/peeraddress.cpp | 37 ++++++++++++++--------------- src/base/bittorrent/peeraddress.h | 2 +- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/base/bittorrent/peeraddress.cpp b/src/base/bittorrent/peeraddress.cpp index 8c4207c60..eed81cebe 100644 --- a/src/base/bittorrent/peeraddress.cpp +++ b/src/base/bittorrent/peeraddress.cpp @@ -29,30 +29,29 @@ #include "peeraddress.h" #include -#include -BitTorrent::PeerAddress BitTorrent::PeerAddress::parse(QString peerAddressStr) +BitTorrent::PeerAddress BitTorrent::PeerAddress::parse(const QString &address) { - PeerAddress addr; - QStringList ipPort; + QVector ipPort; - if ((peerAddressStr[0] == '[') && (peerAddressStr.indexOf("]:") != -1)) // IPv6 - ipPort = peerAddressStr.remove(QChar('[')).split("]:"); - else if (peerAddressStr.indexOf(':') != -1) // IPv4 - ipPort = peerAddressStr.split(':'); - else - return addr; + if (address.startsWith('[') && address.contains("]:")) { // IPv6 + ipPort = address.splitRef("]:"); + ipPort[0] = ipPort[0].mid(1); // chop '[' + } + else if (address.contains(':')) { // IPv4 + ipPort = address.splitRef(':'); + } + else { + return {}; + } - QHostAddress ip(ipPort[0]); + const QHostAddress ip {ipPort[0].toString()}; if (ip.isNull()) - return addr; + return {}; - bool ok; - int port = ipPort[1].toInt(&ok); - if (!ok || (port < 1) || (port > 65535)) - return addr; + const ushort port {ipPort[1].toUShort()}; + if (port == 0) + return {}; - addr.ip = ip; - addr.port = port; - return addr; + return {ip, port}; } diff --git a/src/base/bittorrent/peeraddress.h b/src/base/bittorrent/peeraddress.h index 0a9450ba2..e07243d7b 100644 --- a/src/base/bittorrent/peeraddress.h +++ b/src/base/bittorrent/peeraddress.h @@ -39,6 +39,6 @@ namespace BitTorrent QHostAddress ip; ushort port = 0; - static PeerAddress parse(QString peerAddressStr); + static PeerAddress parse(const QString &address); }; }