@@ -6,7 +6,7 @@ use socket2::{Domain, Protocol, Socket as Socket2, Type};
6
6
use std:: {
7
7
collections:: HashMap ,
8
8
io:: Error ,
9
- net:: { Ipv4Addr , Ipv6Addr , SocketAddr } ,
9
+ net:: { IpAddr , Ipv4Addr , Ipv6Addr , SocketAddr , SocketAddrV4 , SocketAddrV6 } ,
10
10
sync:: Arc ,
11
11
time:: Duration ,
12
12
} ;
@@ -157,14 +157,39 @@ impl Socket {
157
157
}
158
158
159
159
impl ListenConfig {
160
- /// Creates a [`ListenConfig`] with an ipv4-only socket.
161
- pub fn new_ipv4 ( ip : Ipv4Addr , port : u16 ) -> ListenConfig {
162
- Self :: Ipv4 { ip, port }
160
+ /// If an [`IpAddr`] is known, a ListenConfig can be created based on the version. This will
161
+ /// not create a dual stack configuration.
162
+ pub fn from_ip ( ip : IpAddr , port : u16 ) -> ListenConfig {
163
+ match ip {
164
+ IpAddr :: V4 ( ip) => ListenConfig :: Ipv4 { ip, port } ,
165
+ IpAddr :: V6 ( ip) => ListenConfig :: Ipv6 { ip, port } ,
166
+ }
163
167
}
164
168
165
- /// Creates a [`ListenConfig`] with an ipv6-only socket.
166
- pub fn new_ipv6 ( ip : Ipv6Addr , port : u16 ) -> ListenConfig {
167
- Self :: Ipv6 { ip, port }
169
+ /// Allows optional ipv4 and ipv6 addresses to be entered to create a [`ListenConfig`]. If both
170
+ /// are specified a dual-stack configuration will result. This will panic if both parameters
171
+ /// are None.
172
+ pub fn from_two_sockets (
173
+ ipv4 : Option < SocketAddrV4 > ,
174
+ ipv6 : Option < SocketAddrV6 > ,
175
+ ) -> ListenConfig {
176
+ match ( ipv4, ipv6) {
177
+ ( Some ( ipv4) , None ) => ListenConfig :: Ipv4 {
178
+ ip : * ipv4. ip ( ) ,
179
+ port : ipv4. port ( ) ,
180
+ } ,
181
+ ( None , Some ( ipv6) ) => ListenConfig :: Ipv6 {
182
+ ip : * ipv6. ip ( ) ,
183
+ port : ipv6. port ( ) ,
184
+ } ,
185
+ ( Some ( ipv4) , Some ( ipv6) ) => ListenConfig :: DualStack {
186
+ ipv4 : * ipv4. ip ( ) ,
187
+ ipv4_port : ipv4. port ( ) ,
188
+ ipv6 : * ipv6. ip ( ) ,
189
+ ipv6_port : ipv6. port ( ) ,
190
+ } ,
191
+ ( None , None ) => panic ! ( "At least one IP address must be entered." ) ,
192
+ }
168
193
}
169
194
170
195
// Overrides the ipv4 address and port of ipv4 and dual stack configurations. Ipv6
@@ -229,6 +254,21 @@ impl Default for ListenConfig {
229
254
}
230
255
}
231
256
257
+ impl From < SocketAddr > for ListenConfig {
258
+ fn from ( socket_addr : SocketAddr ) -> Self {
259
+ match socket_addr {
260
+ SocketAddr :: V4 ( socket) => ListenConfig :: Ipv4 {
261
+ ip : * socket. ip ( ) ,
262
+ port : socket. port ( ) ,
263
+ } ,
264
+ SocketAddr :: V6 ( socket) => ListenConfig :: Ipv6 {
265
+ ip : * socket. ip ( ) ,
266
+ port : socket. port ( ) ,
267
+ } ,
268
+ }
269
+ }
270
+ }
271
+
232
272
impl Drop for Socket {
233
273
// close the send/recv handlers
234
274
fn drop ( & mut self ) {
0 commit comments