]> git.proxmox.com Git - rustc.git/blob - src/libstd/net/addr.rs
New upstream version 1.13.0+dfsg1
[rustc.git] / src / libstd / net / addr.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use fmt;
12 use hash;
13 use io;
14 use mem;
15 use net::{lookup_host, ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
16 use option;
17 use sys::net::netc as c;
18 use sys_common::{FromInner, AsInner, IntoInner};
19 use vec;
20 use iter;
21 use slice;
22
23 /// Representation of a socket address for networking applications.
24 ///
25 /// A socket address can either represent the IPv4 or IPv6 protocol and is
26 /// paired with at least a port number as well. Each protocol may have more
27 /// specific information about the address available to it as well.
28 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
29 #[stable(feature = "rust1", since = "1.0.0")]
30 pub enum SocketAddr {
31 /// An IPv4 socket address which is a (ip, port) combination.
32 #[stable(feature = "rust1", since = "1.0.0")]
33 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
34 /// An IPv6 socket address
35 #[stable(feature = "rust1", since = "1.0.0")]
36 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
37 }
38
39 /// An IPv4 socket address which is a (ip, port) combination.
40 #[derive(Copy)]
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub struct SocketAddrV4 { inner: c::sockaddr_in }
43
44 /// An IPv6 socket address.
45 #[derive(Copy)]
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
48
49 impl SocketAddr {
50 /// Creates a new socket address from the (ip, port) pair.
51 #[stable(feature = "ip_addr", since = "1.7.0")]
52 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
53 match ip {
54 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
55 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
56 }
57 }
58
59 /// Returns the IP address associated with this socket address.
60 #[stable(feature = "ip_addr", since = "1.7.0")]
61 pub fn ip(&self) -> IpAddr {
62 match *self {
63 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
64 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
65 }
66 }
67
68 /// Change the IP address associated with this socket address.
69 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
70 pub fn set_ip(&mut self, new_ip: IpAddr) {
71 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
72 match (self, new_ip) {
73 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
74 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
75 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
76 }
77 }
78
79 /// Returns the port number associated with this socket address.
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub fn port(&self) -> u16 {
82 match *self {
83 SocketAddr::V4(ref a) => a.port(),
84 SocketAddr::V6(ref a) => a.port(),
85 }
86 }
87
88 /// Change the port number associated with this socket address.
89 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
90 pub fn set_port(&mut self, new_port: u16) {
91 match *self {
92 SocketAddr::V4(ref mut a) => a.set_port(new_port),
93 SocketAddr::V6(ref mut a) => a.set_port(new_port),
94 }
95 }
96 }
97
98 impl SocketAddrV4 {
99 /// Creates a new socket address from the (ip, port) pair.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
102 SocketAddrV4 {
103 inner: c::sockaddr_in {
104 sin_family: c::AF_INET as c::sa_family_t,
105 sin_port: hton(port),
106 sin_addr: *ip.as_inner(),
107 .. unsafe { mem::zeroed() }
108 },
109 }
110 }
111
112 /// Returns the IP address associated with this socket address.
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub fn ip(&self) -> &Ipv4Addr {
115 unsafe {
116 &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
117 }
118 }
119
120 /// Change the IP address associated with this socket address.
121 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
122 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
123 self.inner.sin_addr = *new_ip.as_inner()
124 }
125
126 /// Returns the port number associated with this socket address.
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub fn port(&self) -> u16 {
129 ntoh(self.inner.sin_port)
130 }
131
132 /// Change the port number associated with this socket address.
133 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
134 pub fn set_port(&mut self, new_port: u16) {
135 self.inner.sin_port = hton(new_port);
136 }
137 }
138
139 impl SocketAddrV6 {
140 /// Creates a new socket address from the ip/port/flowinfo/scope_id
141 /// components.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
144 -> SocketAddrV6 {
145 SocketAddrV6 {
146 inner: c::sockaddr_in6 {
147 sin6_family: c::AF_INET6 as c::sa_family_t,
148 sin6_port: hton(port),
149 sin6_addr: *ip.as_inner(),
150 sin6_flowinfo: flowinfo,
151 sin6_scope_id: scope_id,
152 .. unsafe { mem::zeroed() }
153 },
154 }
155 }
156
157 /// Returns the IP address associated with this socket address.
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub fn ip(&self) -> &Ipv6Addr {
160 unsafe {
161 &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
162 }
163 }
164
165 /// Change the IP address associated with this socket address.
166 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
167 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
168 self.inner.sin6_addr = *new_ip.as_inner()
169 }
170
171 /// Returns the port number associated with this socket address.
172 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn port(&self) -> u16 {
174 ntoh(self.inner.sin6_port)
175 }
176
177 /// Change the port number associated with this socket address.
178 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
179 pub fn set_port(&mut self, new_port: u16) {
180 self.inner.sin6_port = hton(new_port);
181 }
182
183 /// Returns the flow information associated with this address,
184 /// corresponding to the `sin6_flowinfo` field in C.
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub fn flowinfo(&self) -> u32 {
187 self.inner.sin6_flowinfo
188 }
189
190 /// Change the flow information associated with this socket address.
191 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
192 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
193 self.inner.sin6_flowinfo = new_flowinfo;
194 }
195
196 /// Returns the scope ID associated with this address,
197 /// corresponding to the `sin6_scope_id` field in C.
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn scope_id(&self) -> u32 {
200 self.inner.sin6_scope_id
201 }
202
203 /// Change the scope ID associated with this socket address.
204 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
205 pub fn set_scope_id(&mut self, new_scope_id: u32) {
206 self.inner.sin6_scope_id = new_scope_id;
207 }
208 }
209
210 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
211 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
212 SocketAddrV4 { inner: addr }
213 }
214 }
215
216 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
217 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
218 SocketAddrV6 { inner: addr }
219 }
220 }
221
222 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
223 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
224 match *self {
225 SocketAddr::V4(ref a) => {
226 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
227 }
228 SocketAddr::V6(ref a) => {
229 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
230 }
231 }
232 }
233 }
234
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl fmt::Display for SocketAddr {
237 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
238 match *self {
239 SocketAddr::V4(ref a) => a.fmt(f),
240 SocketAddr::V6(ref a) => a.fmt(f),
241 }
242 }
243 }
244
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl fmt::Display for SocketAddrV4 {
247 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248 write!(f, "{}:{}", self.ip(), self.port())
249 }
250 }
251
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl fmt::Debug for SocketAddrV4 {
254 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
255 fmt::Display::fmt(self, fmt)
256 }
257 }
258
259 #[stable(feature = "rust1", since = "1.0.0")]
260 impl fmt::Display for SocketAddrV6 {
261 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
262 write!(f, "[{}]:{}", self.ip(), self.port())
263 }
264 }
265
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl fmt::Debug for SocketAddrV6 {
268 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
269 fmt::Display::fmt(self, fmt)
270 }
271 }
272
273 #[stable(feature = "rust1", since = "1.0.0")]
274 impl Clone for SocketAddrV4 {
275 fn clone(&self) -> SocketAddrV4 { *self }
276 }
277 #[stable(feature = "rust1", since = "1.0.0")]
278 impl Clone for SocketAddrV6 {
279 fn clone(&self) -> SocketAddrV6 { *self }
280 }
281
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl PartialEq for SocketAddrV4 {
284 fn eq(&self, other: &SocketAddrV4) -> bool {
285 self.inner.sin_port == other.inner.sin_port &&
286 self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
287 }
288 }
289 #[stable(feature = "rust1", since = "1.0.0")]
290 impl PartialEq for SocketAddrV6 {
291 fn eq(&self, other: &SocketAddrV6) -> bool {
292 self.inner.sin6_port == other.inner.sin6_port &&
293 self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
294 self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
295 self.inner.sin6_scope_id == other.inner.sin6_scope_id
296 }
297 }
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl Eq for SocketAddrV4 {}
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl Eq for SocketAddrV6 {}
302
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl hash::Hash for SocketAddrV4 {
305 fn hash<H: hash::Hasher>(&self, s: &mut H) {
306 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
307 }
308 }
309 #[stable(feature = "rust1", since = "1.0.0")]
310 impl hash::Hash for SocketAddrV6 {
311 fn hash<H: hash::Hasher>(&self, s: &mut H) {
312 (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
313 self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
314 }
315 }
316
317 /// A trait for objects which can be converted or resolved to one or more
318 /// `SocketAddr` values.
319 ///
320 /// This trait is used for generic address resolution when constructing network
321 /// objects. By default it is implemented for the following types:
322 ///
323 /// * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
324 /// identity function.
325 ///
326 /// * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
327 ///
328 /// * `(&str, u16)` - the string should be either a string representation of an
329 /// IP address expected by `FromStr` implementation for `IpvNAddr` or a host
330 /// name.
331 ///
332 /// * `&str` - the string should be either a string representation of a
333 /// `SocketAddr` as expected by its `FromStr` implementation or a string like
334 /// `<host_name>:<port>` pair where `<port>` is a `u16` value.
335 ///
336 /// This trait allows constructing network objects like `TcpStream` or
337 /// `UdpSocket` easily with values of various types for the bind/connection
338 /// address. It is needed because sometimes one type is more appropriate than
339 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
340 /// than manual construction of the corresponding `SocketAddr`, but sometimes
341 /// `SocketAddr` value is *the* main source of the address, and converting it to
342 /// some other type (e.g. a string) just for it to be converted back to
343 /// `SocketAddr` in constructor methods is pointless.
344 ///
345 /// Addresses returned by the operating system that are not IP addresses are
346 /// silently ignored.
347 ///
348 /// Some examples:
349 ///
350 /// ```no_run
351 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
352 ///
353 /// fn main() {
354 /// let ip = Ipv4Addr::new(127, 0, 0, 1);
355 /// let port = 12345;
356 ///
357 /// // The following lines are equivalent modulo possible "localhost" name
358 /// // resolution differences
359 /// let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
360 /// let tcp_s = TcpStream::connect((ip, port));
361 /// let tcp_s = TcpStream::connect(("127.0.0.1", port));
362 /// let tcp_s = TcpStream::connect(("localhost", port));
363 /// let tcp_s = TcpStream::connect("127.0.0.1:12345");
364 /// let tcp_s = TcpStream::connect("localhost:12345");
365 ///
366 /// // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
367 /// // behave similarly
368 /// let tcp_l = TcpListener::bind("localhost:12345");
369 ///
370 /// let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
371 /// udp_s.send_to(&[7], (ip, 23451)).unwrap();
372 /// }
373 /// ```
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub trait ToSocketAddrs {
376 /// Returned iterator over socket addresses which this type may correspond
377 /// to.
378 #[stable(feature = "rust1", since = "1.0.0")]
379 type Iter: Iterator<Item=SocketAddr>;
380
381 /// Converts this object to an iterator of resolved `SocketAddr`s.
382 ///
383 /// The returned iterator may not actually yield any values depending on the
384 /// outcome of any resolution performed.
385 ///
386 /// Note that this function may block the current thread while resolution is
387 /// performed.
388 ///
389 /// # Errors
390 ///
391 /// Any errors encountered during resolution will be returned as an `Err`.
392 #[stable(feature = "rust1", since = "1.0.0")]
393 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
394 }
395
396 #[stable(feature = "rust1", since = "1.0.0")]
397 impl ToSocketAddrs for SocketAddr {
398 type Iter = option::IntoIter<SocketAddr>;
399 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
400 Ok(Some(*self).into_iter())
401 }
402 }
403
404 #[stable(feature = "rust1", since = "1.0.0")]
405 impl ToSocketAddrs for SocketAddrV4 {
406 type Iter = option::IntoIter<SocketAddr>;
407 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
408 SocketAddr::V4(*self).to_socket_addrs()
409 }
410 }
411
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl ToSocketAddrs for SocketAddrV6 {
414 type Iter = option::IntoIter<SocketAddr>;
415 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
416 SocketAddr::V6(*self).to_socket_addrs()
417 }
418 }
419
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl ToSocketAddrs for (IpAddr, u16) {
422 type Iter = option::IntoIter<SocketAddr>;
423 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
424 let (ip, port) = *self;
425 match ip {
426 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
427 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
428 }
429 }
430 }
431
432 #[stable(feature = "rust1", since = "1.0.0")]
433 impl ToSocketAddrs for (Ipv4Addr, u16) {
434 type Iter = option::IntoIter<SocketAddr>;
435 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
436 let (ip, port) = *self;
437 SocketAddrV4::new(ip, port).to_socket_addrs()
438 }
439 }
440
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl ToSocketAddrs for (Ipv6Addr, u16) {
443 type Iter = option::IntoIter<SocketAddr>;
444 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
445 let (ip, port) = *self;
446 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
447 }
448 }
449
450 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
451 let ips = lookup_host(s)?;
452 let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect();
453 Ok(v.into_iter())
454 }
455
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl<'a> ToSocketAddrs for (&'a str, u16) {
458 type Iter = vec::IntoIter<SocketAddr>;
459 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
460 let (host, port) = *self;
461
462 // try to parse the host as a regular IP address first
463 if let Ok(addr) = host.parse::<Ipv4Addr>() {
464 let addr = SocketAddrV4::new(addr, port);
465 return Ok(vec![SocketAddr::V4(addr)].into_iter())
466 }
467 if let Ok(addr) = host.parse::<Ipv6Addr>() {
468 let addr = SocketAddrV6::new(addr, port, 0, 0);
469 return Ok(vec![SocketAddr::V6(addr)].into_iter())
470 }
471
472 resolve_socket_addr(host, port)
473 }
474 }
475
476 // accepts strings like 'localhost:12345'
477 #[stable(feature = "rust1", since = "1.0.0")]
478 impl ToSocketAddrs for str {
479 type Iter = vec::IntoIter<SocketAddr>;
480 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
481 // try to parse as a regular SocketAddr first
482 if let Some(addr) = self.parse().ok() {
483 return Ok(vec![addr].into_iter());
484 }
485
486 macro_rules! try_opt {
487 ($e:expr, $msg:expr) => (
488 match $e {
489 Some(r) => r,
490 None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
491 $msg)),
492 }
493 )
494 }
495
496 // split the string by ':' and convert the second part to u16
497 let mut parts_iter = self.rsplitn(2, ':');
498 let port_str = try_opt!(parts_iter.next(), "invalid socket address");
499 let host = try_opt!(parts_iter.next(), "invalid socket address");
500 let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
501 resolve_socket_addr(host, port)
502 }
503 }
504
505 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
506 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
507 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
508
509 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
510 Ok(self.iter().cloned())
511 }
512 }
513
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
516 type Iter = T::Iter;
517 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
518 (**self).to_socket_addrs()
519 }
520 }
521
522 #[cfg(test)]
523 mod tests {
524 use net::*;
525 use net::test::{tsa, sa6, sa4};
526
527 #[test]
528 fn to_socket_addr_ipaddr_u16() {
529 let a = Ipv4Addr::new(77, 88, 21, 11);
530 let p = 12345;
531 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
532 assert_eq!(Ok(vec![e]), tsa((a, p)));
533 }
534
535 #[test]
536 fn to_socket_addr_str_u16() {
537 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
538 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
539
540 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
541 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
542
543 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
544 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
545 }
546
547 #[test]
548 fn to_socket_addr_str() {
549 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
550 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
551
552 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
553 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
554
555 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
556 assert!(tsa("localhost:23924").unwrap().contains(&a));
557 }
558
559 // FIXME: figure out why this fails on openbsd and bitrig and fix it
560 #[test]
561 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
562 fn to_socket_addr_str_bad() {
563 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
564 }
565
566 #[test]
567 fn set_ip() {
568 fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
569 fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
570
571 let mut v4 = SocketAddrV4::new(ip4(11), 80);
572 assert_eq!(v4.ip(), &ip4(11));
573 v4.set_ip(ip4(12));
574 assert_eq!(v4.ip(), &ip4(12));
575
576 let mut addr = SocketAddr::V4(v4);
577 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
578 addr.set_ip(IpAddr::V4(ip4(13)));
579 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
580 addr.set_ip(IpAddr::V6(ip6(14)));
581 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
582
583 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
584 assert_eq!(v6.ip(), &ip6(1));
585 v6.set_ip(ip6(2));
586 assert_eq!(v6.ip(), &ip6(2));
587
588 let mut addr = SocketAddr::V6(v6);
589 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
590 addr.set_ip(IpAddr::V6(ip6(3)));
591 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
592 addr.set_ip(IpAddr::V4(ip4(4)));
593 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
594 }
595
596 #[test]
597 fn set_port() {
598 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
599 assert_eq!(v4.port(), 80);
600 v4.set_port(443);
601 assert_eq!(v4.port(), 443);
602
603 let mut addr = SocketAddr::V4(v4);
604 assert_eq!(addr.port(), 443);
605 addr.set_port(8080);
606 assert_eq!(addr.port(), 8080);
607
608 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
609 assert_eq!(v6.port(), 80);
610 v6.set_port(443);
611 assert_eq!(v6.port(), 443);
612
613 let mut addr = SocketAddr::V6(v6);
614 assert_eq!(addr.port(), 443);
615 addr.set_port(8080);
616 assert_eq!(addr.port(), 8080);
617 }
618
619 #[test]
620 fn set_flowinfo() {
621 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
622 assert_eq!(v6.flowinfo(), 10);
623 v6.set_flowinfo(20);
624 assert_eq!(v6.flowinfo(), 20);
625 }
626
627 #[test]
628 fn set_scope_id() {
629 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
630 assert_eq!(v6.scope_id(), 10);
631 v6.set_scope_id(20);
632 assert_eq!(v6.scope_id(), 20);
633 }
634 }