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.
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.
17 use net
::{lookup_host, ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr}
;
19 use sys
::net
::netc
as c
;
20 use sys_common
::{FromInner, AsInner, IntoInner}
;
23 /// Representation of a socket address for networking applications.
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")]
31 /// An IPv4 socket address which is a (ip, port) combination.
32 #[stable(feature = "rust1", since = "1.0.0")]
33 V4(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] SocketAddrV4),
34 /// An IPv6 socket address
35 #[stable(feature = "rust1", since = "1.0.0")]
36 V6(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] SocketAddrV6),
39 /// An IPv4 socket address which is a (ip, port) combination.
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub struct SocketAddrV4 { inner: c::sockaddr_in }
44 /// An IPv6 socket address.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
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
{
54 IpAddr
::V4(a
) => SocketAddr
::V4(SocketAddrV4
::new(a
, port
)),
55 IpAddr
::V6(a
) => SocketAddr
::V6(SocketAddrV6
::new(a
, port
, 0, 0)),
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
{
63 SocketAddr
::V4(ref a
) => IpAddr
::V4(*a
.ip()),
64 SocketAddr
::V6(ref a
) => IpAddr
::V6(*a
.ip()),
68 /// Returns the port number associated with this socket address.
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub fn port(&self) -> u16 {
72 SocketAddr
::V4(ref a
) => a
.port(),
73 SocketAddr
::V6(ref a
) => a
.port(),
79 /// Creates a new socket address from the (ip, port) pair.
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub fn new(ip
: Ipv4Addr
, port
: u16) -> SocketAddrV4
{
83 inner
: c
::sockaddr_in
{
84 sin_family
: c
::AF_INET
as c
::sa_family_t
,
86 sin_addr
: *ip
.as_inner(),
87 .. unsafe { mem::zeroed() }
92 /// Returns the IP address associated with this socket address.
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub fn ip(&self) -> &Ipv4Addr
{
96 &*(&self.inner
.sin_addr
as *const c
::in_addr
as *const Ipv4Addr
)
100 /// Returns the port number associated with this socket address.
101 #[stable(feature = "rust1", since = "1.0.0")]
102 pub fn port(&self) -> u16 { ntoh(self.inner.sin_port) }
106 /// Creates a new socket address from the ip/port/flowinfo/scope_id
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub fn new(ip
: Ipv6Addr
, port
: u16, flowinfo
: u32, scope_id
: u32)
112 inner
: c
::sockaddr_in6
{
113 sin6_family
: c
::AF_INET6
as c
::sa_family_t
,
114 sin6_port
: hton(port
),
115 sin6_addr
: *ip
.as_inner(),
116 sin6_flowinfo
: hton(flowinfo
),
117 sin6_scope_id
: hton(scope_id
),
118 .. unsafe { mem::zeroed() }
123 /// Returns the IP address associated with this socket address.
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub fn ip(&self) -> &Ipv6Addr
{
127 &*(&self.inner
.sin6_addr
as *const c
::in6_addr
as *const Ipv6Addr
)
131 /// Returns the port number associated with this socket address.
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub fn port(&self) -> u16 { ntoh(self.inner.sin6_port) }
135 /// Returns the flow information associated with this address,
136 /// corresponding to the `sin6_flowinfo` field in C.
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub fn flowinfo(&self) -> u32 { ntoh(self.inner.sin6_flowinfo) }
140 /// Returns the scope ID associated with this address,
141 /// corresponding to the `sin6_scope_id` field in C.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn scope_id(&self) -> u32 { ntoh(self.inner.sin6_scope_id) }
146 impl FromInner
<c
::sockaddr_in
> for SocketAddrV4
{
147 fn from_inner(addr
: c
::sockaddr_in
) -> SocketAddrV4
{
148 SocketAddrV4 { inner: addr }
152 impl FromInner
<c
::sockaddr_in6
> for SocketAddrV6
{
153 fn from_inner(addr
: c
::sockaddr_in6
) -> SocketAddrV6
{
154 SocketAddrV6 { inner: addr }
158 impl<'a
> IntoInner
<(*const c
::sockaddr
, c
::socklen_t
)> for &'a SocketAddr
{
159 fn into_inner(self) -> (*const c
::sockaddr
, c
::socklen_t
) {
161 SocketAddr
::V4(ref a
) => {
162 (a
as *const _
as *const _
, mem
::size_of_val(a
) as c
::socklen_t
)
164 SocketAddr
::V6(ref a
) => {
165 (a
as *const _
as *const _
, mem
::size_of_val(a
) as c
::socklen_t
)
171 #[stable(feature = "rust1", since = "1.0.0")]
172 impl fmt
::Display
for SocketAddr
{
173 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
175 SocketAddr
::V4(ref a
) => a
.fmt(f
),
176 SocketAddr
::V6(ref a
) => a
.fmt(f
),
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl fmt
::Display
for SocketAddrV4
{
183 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
184 write
!(f
, "{}:{}", self.ip(), self.port())
188 #[stable(feature = "rust1", since = "1.0.0")]
189 impl fmt
::Debug
for SocketAddrV4
{
190 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
191 fmt
::Display
::fmt(self, fmt
)
195 #[stable(feature = "rust1", since = "1.0.0")]
196 impl fmt
::Display
for SocketAddrV6
{
197 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
198 write
!(f
, "[{}]:{}", self.ip(), self.port())
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl fmt
::Debug
for SocketAddrV6
{
204 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
205 fmt
::Display
::fmt(self, fmt
)
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl Clone
for SocketAddrV4
{
211 fn clone(&self) -> SocketAddrV4 { *self }
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl Clone
for SocketAddrV6
{
215 fn clone(&self) -> SocketAddrV6 { *self }
218 #[stable(feature = "rust1", since = "1.0.0")]
219 impl PartialEq
for SocketAddrV4
{
220 fn eq(&self, other
: &SocketAddrV4
) -> bool
{
221 self.inner
.sin_port
== other
.inner
.sin_port
&&
222 self.inner
.sin_addr
.s_addr
== other
.inner
.sin_addr
.s_addr
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl PartialEq
for SocketAddrV6
{
227 fn eq(&self, other
: &SocketAddrV6
) -> bool
{
228 self.inner
.sin6_port
== other
.inner
.sin6_port
&&
229 self.inner
.sin6_addr
.s6_addr
== other
.inner
.sin6_addr
.s6_addr
&&
230 self.inner
.sin6_flowinfo
== other
.inner
.sin6_flowinfo
&&
231 self.inner
.sin6_scope_id
== other
.inner
.sin6_scope_id
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl Eq
for SocketAddrV4 {}
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl Eq
for SocketAddrV6 {}
239 #[stable(feature = "rust1", since = "1.0.0")]
240 impl hash
::Hash
for SocketAddrV4
{
241 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
242 (self.inner
.sin_port
, self.inner
.sin_addr
.s_addr
).hash(s
)
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl hash
::Hash
for SocketAddrV6
{
247 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
248 (self.inner
.sin6_port
, &self.inner
.sin6_addr
.s6_addr
,
249 self.inner
.sin6_flowinfo
, self.inner
.sin6_scope_id
).hash(s
)
253 /// A trait for objects which can be converted or resolved to one or more
254 /// `SocketAddr` values.
256 /// This trait is used for generic address resolution when constructing network
257 /// objects. By default it is implemented for the following types:
259 /// * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
260 /// identity function.
262 /// * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
264 /// * `(&str, u16)` - the string should be either a string representation of an
265 /// IP address expected by `FromStr` implementation for `IpvNAddr` or a host
268 /// * `&str` - the string should be either a string representation of a
269 /// `SocketAddr` as expected by its `FromStr` implementation or a string like
270 /// `<host_name>:<port>` pair where `<port>` is a `u16` value.
272 /// This trait allows constructing network objects like `TcpStream` or
273 /// `UdpSocket` easily with values of various types for the bind/connection
274 /// address. It is needed because sometimes one type is more appropriate than
275 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
276 /// than manual construction of the corresponding `SocketAddr`, but sometimes
277 /// `SocketAddr` value is *the* main source of the address, and converting it to
278 /// some other type (e.g. a string) just for it to be converted back to
279 /// `SocketAddr` in constructor methods is pointless.
284 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
287 /// let ip = Ipv4Addr::new(127, 0, 0, 1);
288 /// let port = 12345;
290 /// // The following lines are equivalent modulo possible "localhost" name
291 /// // resolution differences
292 /// let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
293 /// let tcp_s = TcpStream::connect((ip, port));
294 /// let tcp_s = TcpStream::connect(("127.0.0.1", port));
295 /// let tcp_s = TcpStream::connect(("localhost", port));
296 /// let tcp_s = TcpStream::connect("127.0.0.1:12345");
297 /// let tcp_s = TcpStream::connect("localhost:12345");
299 /// // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
300 /// // behave similarly
301 /// let tcp_l = TcpListener::bind("localhost:12345");
303 /// let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
304 /// udp_s.send_to(&[7], (ip, 23451)).unwrap();
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub trait ToSocketAddrs
{
309 /// Returned iterator over socket addresses which this type may correspond
311 #[stable(feature = "rust1", since = "1.0.0")]
312 type Iter
: Iterator
<Item
=SocketAddr
>;
314 /// Converts this object to an iterator of resolved `SocketAddr`s.
316 /// The returned iterator may not actually yield any values depending on the
317 /// outcome of any resolution performed.
319 /// Note that this function may block the current thread while resolution is
324 /// Any errors encountered during resolution will be returned as an `Err`.
325 #[stable(feature = "rust1", since = "1.0.0")]
326 fn to_socket_addrs(&self) -> io
::Result
<Self::Iter
>;
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl ToSocketAddrs
for SocketAddr
{
331 type Iter
= option
::IntoIter
<SocketAddr
>;
332 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
333 Ok(Some(*self).into_iter())
337 #[stable(feature = "rust1", since = "1.0.0")]
338 impl ToSocketAddrs
for SocketAddrV4
{
339 type Iter
= option
::IntoIter
<SocketAddr
>;
340 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
341 SocketAddr
::V4(*self).to_socket_addrs()
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl ToSocketAddrs
for SocketAddrV6
{
347 type Iter
= option
::IntoIter
<SocketAddr
>;
348 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
349 SocketAddr
::V6(*self).to_socket_addrs()
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl ToSocketAddrs
for (IpAddr
, u16) {
355 type Iter
= option
::IntoIter
<SocketAddr
>;
356 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
357 let (ip
, port
) = *self;
359 IpAddr
::V4(ref a
) => (*a
, port
).to_socket_addrs(),
360 IpAddr
::V6(ref a
) => (*a
, port
).to_socket_addrs(),
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl ToSocketAddrs
for (Ipv4Addr
, u16) {
367 type Iter
= option
::IntoIter
<SocketAddr
>;
368 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
369 let (ip
, port
) = *self;
370 SocketAddrV4
::new(ip
, port
).to_socket_addrs()
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl ToSocketAddrs
for (Ipv6Addr
, u16) {
376 type Iter
= option
::IntoIter
<SocketAddr
>;
377 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
378 let (ip
, port
) = *self;
379 SocketAddrV6
::new(ip
, port
, 0, 0).to_socket_addrs()
383 fn resolve_socket_addr(s
: &str, p
: u16) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
384 let ips
= try
!(lookup_host(s
));
385 let v
: Vec
<_
> = try
!(ips
.map(|a
| {
388 SocketAddr
::V4(ref a
) => {
389 SocketAddr
::V4(SocketAddrV4
::new(*a
.ip(), p
))
391 SocketAddr
::V6(ref a
) => {
392 SocketAddr
::V6(SocketAddrV6
::new(*a
.ip(), p
, a
.flowinfo(),
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl<'a
> ToSocketAddrs
for (&'a
str, u16) {
403 type Iter
= vec
::IntoIter
<SocketAddr
>;
404 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
405 let (host
, port
) = *self;
407 // try to parse the host as a regular IP address first
408 if let Ok(addr
) = host
.parse
::<Ipv4Addr
>() {
409 let addr
= SocketAddrV4
::new(addr
, port
);
410 return Ok(vec
![SocketAddr
::V4(addr
)].into_iter())
412 if let Ok(addr
) = host
.parse
::<Ipv6Addr
>() {
413 let addr
= SocketAddrV6
::new(addr
, port
, 0, 0);
414 return Ok(vec
![SocketAddr
::V6(addr
)].into_iter())
417 resolve_socket_addr(host
, port
)
421 // accepts strings like 'localhost:12345'
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl ToSocketAddrs
for str {
424 type Iter
= vec
::IntoIter
<SocketAddr
>;
425 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
426 // try to parse as a regular SocketAddr first
427 match self.parse().ok() {
428 Some(addr
) => return Ok(vec
![addr
].into_iter()),
432 macro_rules
! try_opt
{
433 ($e
:expr
, $msg
:expr
) => (
436 None
=> return Err(io
::Error
::new(io
::ErrorKind
::InvalidInput
,
442 // split the string by ':' and convert the second part to u16
443 let mut parts_iter
= self.rsplitn(2, '
:'
);
444 let port_str
= try_opt
!(parts_iter
.next(), "invalid socket address");
445 let host
= try_opt
!(parts_iter
.next(), "invalid socket address");
446 let port
: u16 = try_opt
!(port_str
.parse().ok(), "invalid port value");
447 resolve_socket_addr(host
, port
)
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl<'a
, T
: ToSocketAddrs
+ ?Sized
> ToSocketAddrs
for &'a T
{
454 fn to_socket_addrs(&self) -> io
::Result
<T
::Iter
> {
455 (**self).to_socket_addrs()
463 use net
::test
::{tsa, sa6, sa4}
;
466 fn to_socket_addr_ipaddr_u16() {
467 let a
= Ipv4Addr
::new(77, 88, 21, 11);
469 let e
= SocketAddr
::V4(SocketAddrV4
::new(a
, p
));
470 assert_eq
!(Ok(vec
![e
]), tsa((a
, p
)));
474 fn to_socket_addr_str_u16() {
475 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
476 assert_eq
!(Ok(vec
![a
]), tsa(("77.88.21.11", 24352)));
478 let a
= sa6(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
479 assert_eq
!(Ok(vec
![a
]), tsa(("2a02:6b8:0:1::1", 53)));
481 let a
= sa4(Ipv4Addr
::new(127, 0, 0, 1), 23924);
482 assert
!(tsa(("localhost", 23924)).unwrap().contains(&a
));
486 fn to_socket_addr_str() {
487 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
488 assert_eq
!(Ok(vec
![a
]), tsa("77.88.21.11:24352"));
490 let a
= sa6(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
491 assert_eq
!(Ok(vec
![a
]), tsa("[2a02:6b8:0:1::1]:53"));
493 let a
= sa4(Ipv4Addr
::new(127, 0, 0, 1), 23924);
494 assert
!(tsa("localhost:23924").unwrap().contains(&a
));
497 // FIXME: figure out why this fails on openbsd and bitrig and fix it
499 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
500 fn to_socket_addr_str_bad() {
501 assert
!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());