Skip to content

Commit 585becb

Browse files
Copilotrdementi
andcommitted
Add IP address validation in command-line parsing
- Added isValidIPAddress() function to validate IPv4/IPv6 addresses - Validation uses inet_pton() to check address format before passing to Server - Provides clear error message for invalid addresses at command-line parsing stage - Addresses code review feedback to validate user input early Co-authored-by: rdementi <25432609+rdementi@users.noreply.github.com>
1 parent f8294c1 commit 585becb

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/pcm-sensor-server.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3922,6 +3922,27 @@ int startHTTPSServer( const std::string& listenAddr, unsigned short port, std::s
39223922
}
39233923
#endif
39243924

3925+
// Validate IP address string (IPv4 or IPv6)
3926+
bool isValidIPAddress( const std::string& ipAddress ) {
3927+
if ( ipAddress.empty() ) {
3928+
return true; // Empty string is valid - means bind to all interfaces
3929+
}
3930+
3931+
// Try IPv4 first
3932+
struct sockaddr_in sa4;
3933+
if ( 1 == ::inet_pton( AF_INET, ipAddress.c_str(), &(sa4.sin_addr) ) ) {
3934+
return true;
3935+
}
3936+
3937+
// Try IPv6
3938+
struct sockaddr_in6 sa6;
3939+
if ( 1 == ::inet_pton( AF_INET6, ipAddress.c_str(), &(sa6.sin6_addr) ) ) {
3940+
return true;
3941+
}
3942+
3943+
return false;
3944+
}
3945+
39253946
void printHelpText( std::string const & programName ) {
39263947
std::cout << "Usage: " << programName << " [OPTION]\n\n";
39273948
std::cout << "Valid Options:\n";
@@ -4014,6 +4035,11 @@ int mainThrows(int argc, char * argv[]) {
40144035
{
40154036
if ( (++i) < argc ) {
40164037
listenAddress = argv[i];
4038+
if ( !isValidIPAddress( listenAddress ) ) {
4039+
std::cerr << "Error: Invalid IP address '" << listenAddress << "'. ";
4040+
std::cerr << "Please provide a valid IPv4 or IPv6 address.\n";
4041+
exit( 1 );
4042+
}
40174043
} else {
40184044
throw std::runtime_error( "main: Error no listen address argument given" );
40194045
}

0 commit comments

Comments
 (0)