plptools
Loading...
Searching...
No Matches
cli_utils.cc
Go to the documentation of this file.
1/*
2 * This file is part of plptools.
3 *
4 * Copyright (C) 1999 Philip Proudman <philip.proudman@btinternet.com>
5 * Copyright (C) 1999-2002 Fritz Elfert <felfert@to.com>
6 * Copyright (C) 2026 Jason Morley <hello@jbmorley.co.uk>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
20 *
21 */
22
23#include "config.h"
24
25#include "cli_utils.h"
26
27#include <algorithm>
28#include <cctype>
29#include <cstring>
30#include <stdlib.h>
31
32#include <netdb.h>
33
34bool cli_utils::is_number(const std::string &s) {
35 if (s.empty()) {
36 return false;
37 }
38 return std::all_of(s.begin(), s.end(), [](unsigned char c) {
39 return ::isdigit(c);
40 });
41}
42
44 struct servent *se = getservbyname("psion", "tcp");
45 endservent();
46 if (se == nullptr) {
47 return DPORT;
48 }
49 return ntohs(se->s_port);
50}
51
52bool cli_utils::parse_port(const std::string &arg, std::string *host, int *port) {
53
54 if (host == nullptr || port == nullptr) {
55 return false;
56 }
57
58 if (arg.empty()) {
59 return true;
60 }
61
62 size_t pos = arg.find(':');
63 if (pos != std::string::npos) {
64
65 // host.domain:400
66 // 10.0.0.1:400
67
68 std::string hostComponent = arg.substr(0, pos);
69 std::string portComponent = arg.substr(pos + 1);
70 if (hostComponent.empty() || portComponent.empty() || !cli_utils::is_number(portComponent)) {
71 return false;
72 }
73
74 *host = hostComponent;
75 *port = atoi(portComponent.c_str());
76
77 } else if (cli_utils::is_number(arg)) {
78
79 // 400
80
81 *port = atoi(arg.c_str());
82
83 } else {
84
85 // host.domain
86 // host
87 // 10.0.0.1
88
89 *host = arg;
90
91 }
92
93 return true;
94}
bool parse_port(const std::string &arg, std::string *host, int *port)
Definition: cli_utils.cc:52
bool is_number(const std::string &s)
Definition: cli_utils.cc:34
int lookup_default_port()
Definition: cli_utils.cc:43