plptools
Loading...
Searching...
No Matches
cliutils.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 "cliutils.h"
26
27#include <algorithm>
28#include <cctype>
29#include <cstring>
30#include <stdlib.h>
31
32#include <netdb.h>
33#include <arpa/inet.h>
34
35bool cli_utils::is_number(const std::string &s) {
36 if (s.empty()) {
37 return false;
38 }
39 return std::all_of(s.begin(), s.end(), [](unsigned char c) {
40 return ::isdigit(c);
41 });
42}
43
45 struct servent *se = getservbyname("psion", "tcp");
46 endservent();
47 if (se == nullptr) {
48 return DPORT;
49 }
50 return ntohs(se->s_port);
51}
52
53bool cli_utils::parse_port(const std::string &arg, std::string *host, int *port) {
54
55 if (host == nullptr || port == nullptr) {
56 return false;
57 }
58
59 if (arg.empty()) {
60 return true;
61 }
62
63 size_t pos = arg.find(':');
64 if (pos != std::string::npos) {
65
66 // host.domain:400
67 // 10.0.0.1:400
68
69 std::string hostComponent = arg.substr(0, pos);
70 std::string portComponent = arg.substr(pos + 1);
71 if (hostComponent.empty() || portComponent.empty() || !cli_utils::is_number(portComponent)) {
72 return false;
73 }
74
75 *host = hostComponent;
76 *port = atoi(portComponent.c_str());
77
78 } else if (cli_utils::is_number(arg)) {
79
80 // 400
81
82 *port = atoi(arg.c_str());
83
84 } else {
85
86 // host.domain
87 // host
88 // 10.0.0.1
89
90 *host = arg;
91
92 }
93
94 return true;
95}
bool parse_port(const std::string &arg, std::string *host, int *port)
Definition: cliutils.cc:53
bool is_number(const std::string &s)
Definition: cliutils.cc:35
int lookup_default_port()
Definition: cliutils.cc:44