1 /* 2 Copyright (c) 2013 yvt, learn_more 3 4 This file is part of OpenSpades. 5 6 OpenSpades is free software: you can redistribute it and/or modify 7 it under the terms of the GNU General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 OpenSpades is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU General Public License for more details. 15 16 You should have received a copy of the GNU General Public License 17 along with OpenSpades. If not, see <http://www.gnu.org/licenses/>. 18 19 */ 20 21 #include <enet/enet.h> 22 #include <regex> 23 24 #include "ServerAddress.h" 25 26 namespace spades { 27 28 // unsigned long version of atol, cross-platform (including MSVC) ParseIntegerAddress(const std::string & str)29 uint32_t ServerAddress::ParseIntegerAddress(const std::string &str) { 30 uint32_t vl = 0; 31 for (size_t i = 0; i < str.size(); i++) { 32 char c = str[i]; 33 if (c >= '0' && c <= '9') { 34 vl *= 10; 35 vl += (uint32_t)(c - '0'); 36 } else { 37 break; 38 } 39 } 40 41 return vl; 42 } 43 ServerAddress(std::string address,ProtocolVersion version)44 ServerAddress::ServerAddress(std::string address, ProtocolVersion version) 45 : mAddress(address), mVersion(version) { 46 static std::regex v075regex {"(.*):0?\\.?75"}; 47 static std::regex v076regex {"(.*):0?\\.?76"}; 48 49 std::smatch matchResult; 50 51 if (std::regex_match(address, matchResult, v075regex)) { 52 version = ProtocolVersion::v075; 53 mAddress = matchResult[1]; 54 } else if (std::regex_match(address, matchResult, v076regex)) { 55 version = ProtocolVersion::v076; 56 mAddress = matchResult[1]; 57 } 58 } 59 StripProtocol(const std::string & address)60 std::string ServerAddress::StripProtocol(const std::string &address) { 61 if (address.find("aos:///") == 0) { 62 return address.substr(7); 63 } else if (address.find("aos://") == 0) { 64 return address.substr(6); 65 } 66 return address; 67 } 68 GetENetAddress() const69 ENetAddress ServerAddress::GetENetAddress() const { 70 std::string address = StripProtocol(mAddress); 71 72 ENetAddress addr; 73 size_t pos = address.find(':'); 74 if (pos == std::string::npos) { 75 // addr = address; 76 addr.port = 32887; 77 } else { 78 addr.port = atoi(address.substr(pos + 1).c_str()); 79 address = address.substr(0, pos); 80 } 81 82 if (address.find('.') != std::string::npos) { 83 enet_address_set_host(&addr, address.c_str()); 84 } else { 85 addr.host = ParseIntegerAddress(address); 86 } 87 return addr; 88 } 89 ToString(bool includeProtocol) const90 std::string ServerAddress::ToString(bool includeProtocol) const { 91 if (!includeProtocol) { 92 return StripProtocol(mAddress); 93 } 94 return mAddress; 95 } 96 97 }; // namespace spades 98