felixfaisal commented on code in PR #2923: URL: https://github.com/apache/iggy/pull/2923#discussion_r2999625929
########## core/common/src/utils/net.rs: ########## @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +use crate::IggyError; + +/// Validates that `addr` is syntactically a valid `host:port` string. +/// Does NOT perform DNS resolution. +/// +/// Accepted formats: +/// - `hostname:port` (e.g. `iggy-server:8090`, `localhost:8090`) +/// - `ipv4:port` (e.g. `127.0.0.1:8090`) +/// - `[ipv6]:port` (e.g. `[::1]:8090`) +/// +/// Rejected formats: +/// - Bare IPv6 without brackets (e.g. `::1:8080`) — ambiguous due to colons +/// - Missing port (e.g. `localhost`) +/// - Invalid port (e.g. `localhost:abc`, `localhost:65536`) +pub fn parse_server_address(addr: &str) -> Result<(), IggyError> { + if let Some(rest) = addr.strip_prefix('[') { + // Bracketed IPv6: "[::1]:port" + let close = rest.find(']').ok_or(IggyError::InvalidIpAddress( + addr.to_string(), + "".to_string(), + ))?; + let port_str = rest[close + 1..] + .strip_prefix(':') + .ok_or(IggyError::InvalidIpAddress( + addr.to_string(), + "".to_string(), + ))?; + + port_str.parse::<u16>().map_err(|_| { + IggyError::InvalidIpAddress(rest[0..close].to_string(), port_str.to_string()) + })?; + + return Ok(()); + } + // hostname:port or IPv4:port — rsplit_once to split at last colon + let (host, port_str) = addr.rsplit_once(':').ok_or(IggyError::InvalidIpAddress( + addr.to_string(), + "".to_string(), + ))?; + + if host.is_empty() { Review Comment: Created a separate function, to check if valid IPv4 address and if not check if valid hostname, added a couple of unit tests using claude. ✅ I was thinking if i should use regex or not, and ultimately decided to do it this way. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
