From 7481ba561822ae1a75029bc53f79cb7f4a892f93 Mon Sep 17 00:00:00 2001 From: Trent Nelson Date: Wed, 11 Nov 2020 19:27:03 -0700 Subject: [PATCH] ip-echo-server: Add helper to compute reply length --- net-utils/src/ip_echo_server.rs | 8 ++------ net-utils/src/lib.rs | 4 ++++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/net-utils/src/ip_echo_server.rs b/net-utils/src/ip_echo_server.rs index 52dc7c0e25..4ba62a6ea1 100644 --- a/net-utils/src/ip_echo_server.rs +++ b/net-utils/src/ip_echo_server.rs @@ -1,4 +1,4 @@ -use crate::HEADER_LENGTH; +use crate::{ip_echo_server_reply_length, HEADER_LENGTH}; use bytes::Bytes; use log::*; use serde_derive::{Deserialize, Serialize}; @@ -177,11 +177,7 @@ pub fn ip_echo_server(tcp: std::net::TcpListener) -> IpEchoServer { } else { // "\0\0\0\0" header is added to ensure a valid response will never // conflict with the first four bytes of a valid HTTP response. - let mut bytes = vec![ - 0; - HEADER_LENGTH + bincode::serialized_size(&peer_addr.ip()).unwrap() - as usize - ]; + let mut bytes = vec![0u8; ip_echo_server_reply_length()]; bincode::serialize_into(&mut bytes[HEADER_LENGTH..], &peer_addr.ip()) .unwrap(); Ok(Bytes::from(bytes)) diff --git a/net-utils/src/lib.rs b/net-utils/src/lib.rs index 547ee4f9fc..72f6057f2d 100644 --- a/net-utils/src/lib.rs +++ b/net-utils/src/lib.rs @@ -23,6 +23,10 @@ pub struct UdpSocketPair { pub type PortRange = (u16, u16); pub(crate) const HEADER_LENGTH: usize = 4; +pub(crate) fn ip_echo_server_reply_length() -> usize { + let largest_ip_addr = IpAddr::from([0u16; 8]); // IPv6 variant + HEADER_LENGTH + bincode::serialized_size(&largest_ip_addr).unwrap() as usize +} fn ip_echo_server_request( ip_echo_server_addr: &SocketAddr,