1616 */
1717#include " SocketUtil.h"
1818
19- #include < cstdlib> // std::abort
20- #include < cstring> // std::memcpy, std::memset
19+ #include < algorithm> // std::all_of
20+ #include < cctype> // std::isdigit
21+ #include < cstdlib> // std::abort
22+ #include < cstring> // std::memcpy, std::memset
2123
2224#include < iostream>
2325#include < limits>
24- #include < memory> // std::unique_ptr
26+ #include < memory> // std::unique_ptr
2527#include < stdexcept> // std::invalid_argument, std::runtime_error
2628#include < string>
2729
@@ -46,7 +48,7 @@ void SafeMemcpy(void* dest, size_t dest_size, const void* src, size_t src_size)
4648 if (src_size > dest_size) {
4749 throw std::invalid_argument (" source size exceeds destination buffer size" );
4850 }
49- std::memcpy (dest, src, src_size);
51+ std::memmove (dest, src, src_size);
5052}
5153
5254std::unique_ptr<sockaddr_storage> SockaddrToStorage (const sockaddr* src) {
@@ -134,15 +136,18 @@ std::unique_ptr<sockaddr_storage> StringToSockaddr(const std::string& addr) {
134136 uint16_t port_num = 0 ;
135137
136138 if (!port_str.empty ()) {
139+ if (!std::all_of (port_str.begin (), port_str.end (), [](unsigned char c) { return std::isdigit (c); })) {
140+ throw std::invalid_argument (" port contains non-digit characters: " + port_str);
141+ }
137142 try {
138143 uint32_t n = std::stoul (port_str);
144+ if (n == 0 ) {
145+ throw std::invalid_argument (" port cannot be zero" );
146+ }
139147 if (n > std::numeric_limits<uint16_t >::max ()) {
140148 throw std::out_of_range (" port is too large: " + std::to_string (n) +
141149 " (max: " + std::to_string (std::numeric_limits<uint16_t >::max ()) + " )" );
142150 }
143- if (n == 0 ) {
144- throw std::invalid_argument (" port cannot be zero" );
145- }
146151 port_num = htons (static_cast <uint16_t >(n));
147152 } catch (const std::exception& e) {
148153 throw std::invalid_argument (" invalid port: " + port_str + " (" + e.what () + " )" );
0 commit comments