pub struct IpAddrWithPort { /* private fields */ }
Expand description

IP 地址和端口号

用来表示一个七牛服务器的地址,端口号是可选的,如果不提供,则根据传输协议判定默认的端口号。

Implementations§

创建 IP 地址和端口号

IP 地址可以是 IPv4 地址或 IPv6 地址

Examples found in repository?
src/regions/endpoint.rs (line 212)
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    fn from(ip_addr: IpAddr) -> Self {
        Self::new(ip_addr, None)
    }
}

impl From<Ipv4Addr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: Ipv4Addr) -> Self {
        Self::new(IpAddr::from(ip_addr), None)
    }
}

impl From<Ipv6Addr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: Ipv6Addr) -> Self {
        Self::new(IpAddr::from(ip_addr), None)
    }
}

impl From<IpAddrWithPort> for IpAddr {
    #[inline]
    fn from(ip_addr_with_port: IpAddrWithPort) -> Self {
        ip_addr_with_port.ip_addr()
    }
}

impl From<SocketAddr> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddr) -> Self {
        Self::new(socket_addr.ip(), NonZeroU16::new(socket_addr.port()))
    }
}

impl From<SocketAddrV4> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddrV4) -> Self {
        SocketAddr::from(socket_addr).into()
    }
}

impl From<SocketAddrV6> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddrV6) -> Self {
        SocketAddr::from(socket_addr).into()
    }
}

impl From<(IpAddr, u16)> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr_with_port: (IpAddr, u16)) -> Self {
        Self::new(ip_addr_with_port.0, NonZeroU16::new(ip_addr_with_port.1))
    }
}

impl From<(IpAddr, Option<NonZeroU16>)> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr_with_port: (IpAddr, Option<NonZeroU16>)) -> Self {
        Self::new(ip_addr_with_port.0, ip_addr_with_port.1)
    }
}

/// 解析 IP 地址和端口号错误
#[derive(Error, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum IpAddrWithPortParseError {
    /// 地址解析错误
    #[error("invalid ip address: {0}")]
    ParseError(#[from] AddrParseError),
}

impl FromStr for IpAddrWithPort {
    type Err = IpAddrWithPortParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parse_result: Result<SocketAddr, AddrParseError> = s.parse();
        if let Ok(socket_addr) = parse_result {
            return Ok(socket_addr.into());
        }
        let ip_addr: IpAddr = s.parse()?;
        Ok(ip_addr.into())
    }
}

/// 终端地址
///
/// 该类型是枚举类型,表示一个域名和端口号,或 IP 地址和端口号
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "ty")]
#[non_exhaustive]
pub enum Endpoint {
    /// 域名和端口号
    DomainWithPort(DomainWithPort),

    /// IP 地址和端口号
    IpAddrWithPort(IpAddrWithPort),
}

impl Endpoint {
    /// 基于域名创建终端地址
    #[inline]
    pub fn new_from_domain(domain: impl Into<String>) -> Self {
        Self::DomainWithPort(DomainWithPort {
            domain: domain.into().into_boxed_str(),
            port: None,
        })
    }

    /// 基于域名和端口号创建终端地址
    #[inline]
    pub fn new_from_domain_with_port(domain: impl Into<String>, port: u16) -> Self {
        Self::DomainWithPort(DomainWithPort {
            domain: domain.into().into_boxed_str(),
            port: NonZeroU16::new(port),
        })
    }

    /// 基于 IP 地址创建终端地址
    ///
    /// IP 地址可以是 IPv4 地址或 IPv6 地址
    #[inline]
    pub const fn new_from_ip_addr(ip_addr: IpAddr) -> Self {
        Self::IpAddrWithPort(IpAddrWithPort { ip_addr, port: None })
    }

    /// 基于套接字地址创建终端地址
    ///
    /// 套接字地址可以是 IPv4 地址加端口号,或 IPv6 地址加端口号
    #[inline]
    pub fn new_from_socket_addr(addr: SocketAddr) -> Self {
        Self::IpAddrWithPort(IpAddrWithPort {
            ip_addr: addr.ip(),
            port: NonZeroU16::new(addr.port()),
        })
    }

    /// 如果终端地址包含域名,则获得域名
    #[inline]
    pub fn domain(&self) -> Option<&str> {
        match self {
            Self::DomainWithPort(domain_with_port) => Some(domain_with_port.domain()),
            _ => None,
        }
    }

    /// 如果终端地址包含 IP 地址,则获得域名
    #[inline]
    pub fn ip_addr(&self) -> Option<IpAddr> {
        match self {
            Self::IpAddrWithPort(ip_addr_with_port) => Some(ip_addr_with_port.ip_addr()),
            _ => None,
        }
    }

    /// 获得端口号
    #[inline]
    pub fn port(&self) -> Option<NonZeroU16> {
        match self {
            Self::DomainWithPort(domain_with_port) => domain_with_port.port(),
            Self::IpAddrWithPort(ip_addr_with_port) => ip_addr_with_port.port(),
        }
    }
}

impl Display for Endpoint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DomainWithPort(domain) => write!(f, "{domain}"),
            Self::IpAddrWithPort(ip_addr) => write!(f, "{ip_addr}"),
        }
    }
}

impl From<DomainWithPort> for Endpoint {
    #[inline]
    fn from(domain_with_port: DomainWithPort) -> Self {
        Self::DomainWithPort(domain_with_port)
    }
}

impl From<IpAddrWithPort> for Endpoint {
    #[inline]
    fn from(ip_addr_with_port: IpAddrWithPort) -> Self {
        Self::IpAddrWithPort(ip_addr_with_port)
    }
}

impl<'a> From<&'a str> for Endpoint {
    #[inline]
    fn from(domain: &'a str) -> Self {
        DomainWithPort::new(domain, None).into()
    }
}

impl From<Box<str>> for Endpoint {
    #[inline]
    fn from(domain: Box<str>) -> Self {
        DomainWithPort::new(domain, None).into()
    }
}

impl From<(Box<str>, u16)> for Endpoint {
    #[inline]
    fn from(domain_with_port: (Box<str>, u16)) -> Self {
        DomainWithPort::new(domain_with_port.0, NonZeroU16::new(domain_with_port.1)).into()
    }
}

impl From<(Box<str>, NonZeroU16)> for Endpoint {
    #[inline]
    fn from(domain_with_port: (Box<str>, NonZeroU16)) -> Self {
        DomainWithPort::new(domain_with_port.0, Some(domain_with_port.1)).into()
    }
}

impl From<Authority> for Endpoint {
    #[inline]
    fn from(authority: Authority) -> Self {
        DomainWithPort::from(authority).into()
    }
}

impl From<String> for Endpoint {
    #[inline]
    fn from(domain: String) -> Self {
        DomainWithPort::new(domain, None).into()
    }
}

impl From<(String, u16)> for Endpoint {
    #[inline]
    fn from(domain_with_port: (String, u16)) -> Self {
        DomainWithPort::new(domain_with_port.0, NonZeroU16::new(domain_with_port.1)).into()
    }
}

impl From<(String, NonZeroU16)> for Endpoint {
    #[inline]
    fn from(domain_with_port: (String, NonZeroU16)) -> Self {
        DomainWithPort::new(domain_with_port.0, Some(domain_with_port.1)).into()
    }
}

impl From<IpAddr> for Endpoint {
    #[inline]
    fn from(ip_addr: IpAddr) -> Self {
        IpAddrWithPort::new(ip_addr, None).into()
    }
}

impl From<Ipv4Addr> for Endpoint {
    #[inline]
    fn from(ip_addr: Ipv4Addr) -> Self {
        IpAddr::from(ip_addr).into()
    }
}

impl From<Ipv6Addr> for Endpoint {
    #[inline]
    fn from(ip_addr: Ipv6Addr) -> Self {
        IpAddr::from(ip_addr).into()
    }
}

impl From<SocketAddr> for Endpoint {
    #[inline]
    fn from(socket_addr: SocketAddr) -> Self {
        IpAddrWithPort::new(socket_addr.ip(), NonZeroU16::new(socket_addr.port())).into()
    }
More examples
Hide additional examples
src/client/chooser/subnet.rs (line 174)
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    fn get_network_address(&self, addr: IpAddrWithPort) -> Subnet {
        let subnet = match addr.ip_addr() {
            IpAddr::V4(ipv4_addr) => {
                let ipv4_network_addr =
                    get_network_address_of_ipv4_addr(ipv4_addr, self.inner.ipv4_netmask_prefix_length);
                IpAddr::V4(ipv4_network_addr)
            }
            IpAddr::V6(ipv6_addr) => {
                let ipv6_network_addr =
                    get_network_address_of_ipv6_addr(ipv6_addr, self.inner.ipv6_netmask_prefix_length);
                IpAddr::V6(ipv6_network_addr)
            }
        };
        return Subnet(IpAddrWithPort::new(subnet, addr.port()));

        fn get_network_address_of_ipv4_addr(addr: Ipv4Addr, prefix: u8) -> Ipv4Addr {
            Ipv4Net::new(addr, prefix).unwrap().network()
        }

        fn get_network_address_of_ipv6_addr(addr: Ipv6Addr, prefix: u8) -> Ipv6Addr {
            Ipv6Net::new(addr, prefix).unwrap().network()
        }
    }
src/client/call/utils.rs (line 343)
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
pub(super) fn resolve(
    request: &InnerRequestParts<'_>,
    domain_with_port: &DomainWithPort,
    extensions: &mut Extensions,
    retried: &RetriedStatsInfo,
) -> Result<Vec<IpAddrWithPort>, TryError> {
    let answers = with_resolve_domain(request, domain_with_port.domain(), extensions, retried, || {
        request.http_client().resolver().resolve(
            domain_with_port.domain(),
            ResolveOptions::builder().retried(retried).build(),
        )
    })?;
    return Ok(answers
        .into_ip_addrs()
        .iter()
        .map(|&ip| IpAddrWithPort::new(ip, domain_with_port.port()))
        .collect());

    fn with_resolve_domain(
        request: &InnerRequestParts<'_>,
        domain: &str,
        extensions: &mut Extensions,
        retried: &RetriedStatsInfo,
        f: impl FnOnce() -> ResolveResult,
    ) -> Result<ResolveAnswers, TryError> {
        call_to_resolve_domain_callbacks(request, domain, extensions, retried)?;
        let answers = f().map_err(|err| TryError::new(err, RetryDecision::TryNextServer.into()))?;
        call_domain_resolved_callbacks(request, domain, &answers, extensions, retried)?;
        Ok(answers)
    }
}

pub(super) fn choose(
    request: &InnerRequestParts<'_>,
    ips: &[IpAddrWithPort],
    extensions: &mut Extensions,
    retried: &RetriedStatsInfo,
) -> Result<Vec<IpAddrWithPort>, TryError> {
    call_to_choose_ips_callbacks(request, ips, extensions, retried)?;
    let chosen_ips = request
        .http_client()
        .chooser()
        .choose(ips, Default::default())
        .into_ip_addrs();
    call_ips_chosen_callbacks(request, ips, &chosen_ips, extensions, retried)?;
    Ok(chosen_ips)
}

pub(super) fn judge(mut response: SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<SyncResponse> {
    return match response.status_code().as_u16() {
        0..=199 | 300..=399 => Err(make_unexpected_status_code_error(response.parts(), retried)),
        200..=299 => {
            check_x_req_id(&mut response, retried)?;
            Ok(response)
        }
        _ => to_status_code_error(response, retried),
    };

    fn to_status_code_error(response: SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<SyncResponse> {
        let status_code = response.status_code();
        let (parts, body) = response.parse_json::<ErrorResponseBody>()?.into_parts_and_body();
        Err(
            ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
                .response_parts(&parts)
                .retried(retried),
        )
    }
}

fn check_x_req_id(response: &mut SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
    if response.x_reqid().is_some() {
        Ok(())
    } else {
        Err(make_malicious_response(response.parts(), retried).read_response_body_sample(response.body_mut())?)
    }
}

#[cfg(feature = "async")]
async fn async_check_x_req_id(response: &mut AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
    if response.x_reqid().is_some() {
        Ok(())
    } else {
        Err(make_malicious_response(response.parts(), retried)
            .async_read_response_body_sample(response.body_mut())
            .await?)
    }
}

fn make_malicious_response(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
    ResponseError::new_with_msg(
        ResponseErrorKind::MaliciousResponse,
        "cannot find X-ReqId header from response, might be malicious response",
    )
    .response_parts(parts)
    .retried(retried)
}

fn make_unexpected_status_code_error(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
    ResponseError::new_with_msg(
        ResponseErrorKind::UnexpectedStatusCode(parts.status_code()),
        format!("status code {} is unexpected", parts.status_code()),
    )
    .response_parts(parts)
    .retried(retried)
}

#[cfg(feature = "async")]
mod async_utils {
    use super::{
        super::super::{AsyncResponse, InnerRequestParts},
        *,
    };
    use qiniu_http::AsyncRequest as AsyncHttpRequest;
    use std::future::Future;

    pub(in super::super) async fn sign_async_request(
        request: &mut AsyncHttpRequest<'_>,
        authorization: Option<&Authorization<'_>>,
        retried: &RetriedStatsInfo,
    ) -> Result<(), TryError> {
        if let Some(authorization) = authorization {
            authorization
                .async_sign(request)
                .await
                .map_err(|err| handle_sign_request_error(err, retried))?;
        }
        Ok(())
    }

    pub(in super::super) async fn async_resolve(
        parts: &InnerRequestParts<'_>,
        domain_with_port: &DomainWithPort,
        extensions: &mut Extensions,
        retried: &RetriedStatsInfo,
    ) -> Result<Vec<IpAddrWithPort>, TryError> {
        let answers = with_resolve_domain(parts, domain_with_port.domain(), extensions, retried, || async {
            parts
                .http_client()
                .resolver()
                .async_resolve(
                    domain_with_port.domain(),
                    ResolveOptions::builder().retried(retried).build(),
                )
                .await
        });
        return Ok(answers
            .await?
            .into_ip_addrs()
            .iter()
            .map(|&ip| IpAddrWithPort::new(ip, domain_with_port.port()))
            .collect());

        async fn with_resolve_domain<F: FnOnce() -> Fu, Fu: Future<Output = ResolveResult>>(
            parts: &InnerRequestParts<'_>,
            domain: &str,
            extensions: &mut Extensions,
            retried: &RetriedStatsInfo,
            f: F,
        ) -> Result<ResolveAnswers, TryError> {
            call_to_resolve_domain_callbacks(parts, domain, extensions, retried)?;
            let answers = f()
                .await
                .map_err(|err| TryError::new(err, RetryDecision::TryNextServer.into()))?;
            call_domain_resolved_callbacks(parts, domain, &answers, extensions, retried)?;
            Ok(answers)
        }
    }

获取 IP 地址

Examples found in repository?
src/regions/endpoint.rs (line 199)
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(port) = self.port() {
            SocketAddr::new(self.ip_addr(), port.get()).fmt(f)
        } else {
            match self.ip_addr() {
                IpAddr::V4(ip) => ip.fmt(f),
                IpAddr::V6(ip) => write!(f, "[{ip}]"),
            }
        }
    }
}

impl From<IpAddr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: IpAddr) -> Self {
        Self::new(ip_addr, None)
    }
}

impl From<Ipv4Addr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: Ipv4Addr) -> Self {
        Self::new(IpAddr::from(ip_addr), None)
    }
}

impl From<Ipv6Addr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: Ipv6Addr) -> Self {
        Self::new(IpAddr::from(ip_addr), None)
    }
}

impl From<IpAddrWithPort> for IpAddr {
    #[inline]
    fn from(ip_addr_with_port: IpAddrWithPort) -> Self {
        ip_addr_with_port.ip_addr()
    }
}

impl From<SocketAddr> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddr) -> Self {
        Self::new(socket_addr.ip(), NonZeroU16::new(socket_addr.port()))
    }
}

impl From<SocketAddrV4> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddrV4) -> Self {
        SocketAddr::from(socket_addr).into()
    }
}

impl From<SocketAddrV6> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddrV6) -> Self {
        SocketAddr::from(socket_addr).into()
    }
}

impl From<(IpAddr, u16)> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr_with_port: (IpAddr, u16)) -> Self {
        Self::new(ip_addr_with_port.0, NonZeroU16::new(ip_addr_with_port.1))
    }
}

impl From<(IpAddr, Option<NonZeroU16>)> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr_with_port: (IpAddr, Option<NonZeroU16>)) -> Self {
        Self::new(ip_addr_with_port.0, ip_addr_with_port.1)
    }
}

/// 解析 IP 地址和端口号错误
#[derive(Error, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum IpAddrWithPortParseError {
    /// 地址解析错误
    #[error("invalid ip address: {0}")]
    ParseError(#[from] AddrParseError),
}

impl FromStr for IpAddrWithPort {
    type Err = IpAddrWithPortParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parse_result: Result<SocketAddr, AddrParseError> = s.parse();
        if let Ok(socket_addr) = parse_result {
            return Ok(socket_addr.into());
        }
        let ip_addr: IpAddr = s.parse()?;
        Ok(ip_addr.into())
    }
}

/// 终端地址
///
/// 该类型是枚举类型,表示一个域名和端口号,或 IP 地址和端口号
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "ty")]
#[non_exhaustive]
pub enum Endpoint {
    /// 域名和端口号
    DomainWithPort(DomainWithPort),

    /// IP 地址和端口号
    IpAddrWithPort(IpAddrWithPort),
}

impl Endpoint {
    /// 基于域名创建终端地址
    #[inline]
    pub fn new_from_domain(domain: impl Into<String>) -> Self {
        Self::DomainWithPort(DomainWithPort {
            domain: domain.into().into_boxed_str(),
            port: None,
        })
    }

    /// 基于域名和端口号创建终端地址
    #[inline]
    pub fn new_from_domain_with_port(domain: impl Into<String>, port: u16) -> Self {
        Self::DomainWithPort(DomainWithPort {
            domain: domain.into().into_boxed_str(),
            port: NonZeroU16::new(port),
        })
    }

    /// 基于 IP 地址创建终端地址
    ///
    /// IP 地址可以是 IPv4 地址或 IPv6 地址
    #[inline]
    pub const fn new_from_ip_addr(ip_addr: IpAddr) -> Self {
        Self::IpAddrWithPort(IpAddrWithPort { ip_addr, port: None })
    }

    /// 基于套接字地址创建终端地址
    ///
    /// 套接字地址可以是 IPv4 地址加端口号,或 IPv6 地址加端口号
    #[inline]
    pub fn new_from_socket_addr(addr: SocketAddr) -> Self {
        Self::IpAddrWithPort(IpAddrWithPort {
            ip_addr: addr.ip(),
            port: NonZeroU16::new(addr.port()),
        })
    }

    /// 如果终端地址包含域名,则获得域名
    #[inline]
    pub fn domain(&self) -> Option<&str> {
        match self {
            Self::DomainWithPort(domain_with_port) => Some(domain_with_port.domain()),
            _ => None,
        }
    }

    /// 如果终端地址包含 IP 地址,则获得域名
    #[inline]
    pub fn ip_addr(&self) -> Option<IpAddr> {
        match self {
            Self::IpAddrWithPort(ip_addr_with_port) => Some(ip_addr_with_port.ip_addr()),
            _ => None,
        }
    }
More examples
Hide additional examples
src/client/chooser/subnet.rs (line 162)
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    fn get_network_address(&self, addr: IpAddrWithPort) -> Subnet {
        let subnet = match addr.ip_addr() {
            IpAddr::V4(ipv4_addr) => {
                let ipv4_network_addr =
                    get_network_address_of_ipv4_addr(ipv4_addr, self.inner.ipv4_netmask_prefix_length);
                IpAddr::V4(ipv4_network_addr)
            }
            IpAddr::V6(ipv6_addr) => {
                let ipv6_network_addr =
                    get_network_address_of_ipv6_addr(ipv6_addr, self.inner.ipv6_netmask_prefix_length);
                IpAddr::V6(ipv6_network_addr)
            }
        };
        return Subnet(IpAddrWithPort::new(subnet, addr.port()));

        fn get_network_address_of_ipv4_addr(addr: Ipv4Addr, prefix: u8) -> Ipv4Addr {
            Ipv4Net::new(addr, prefix).unwrap().network()
        }

        fn get_network_address_of_ipv6_addr(addr: Ipv6Addr, prefix: u8) -> Ipv6Addr {
            Ipv6Net::new(addr, prefix).unwrap().network()
        }
    }
src/client/call/utils.rs (line 91)
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    fn _make_url(
        domain_or_ip: &DomainOrIpAddr,
        request: &InnerRequestParts<'_>,
    ) -> Result<(Uri, Vec<IpAddr>), InvalidUri> {
        let mut resolved_ip_addrs = Vec::new();
        let scheme = if request.use_https() {
            Scheme::HTTPS
        } else {
            Scheme::HTTP
        };

        let authority: Authority = match domain_or_ip {
            DomainOrIpAddr::Domain {
                domain_with_port,
                resolved_ips,
            } => {
                resolved_ip_addrs = resolved_ips.iter().map(|resolved| resolved.ip_addr()).collect();
                let mut authority = domain_with_port.domain().to_owned();
                if let Some(port) = domain_with_port.port() {
                    authority.push(':');
                    authority.push_str(&port.get().to_string());
                }
                authority.parse()?
            }
            DomainOrIpAddr::IpAddr(ip_addr_with_port) => ip_addr_with_port.to_string().parse()?,
        };
        let mut path_and_query = if request.path().starts_with('/') {
            request.path().to_owned()
        } else {
            "/".to_owned() + request.path()
        };
        if !request.query().is_empty() || !request.query_pairs().is_empty() {
            path_and_query.push('?');
            let path_len = path_and_query.len();
            if !request.query().is_empty() {
                path_and_query.push_str(request.query());
            }
            let mut serializer = form_urlencoded::Serializer::for_suffix(&mut path_and_query, path_len);
            serializer.extend_pairs(request.query_pairs().iter());
            serializer.finish();
        }
        let path_and_query: PathAndQuery = path_and_query.parse()?;

        let url = Uri::builder()
            .scheme(scheme)
            .authority(authority)
            .path_and_query(path_and_query)
            .build()
            .unwrap();
        Ok((url, resolved_ip_addrs))
    }

获取端口号

Examples found in repository?
src/regions/endpoint.rs (line 198)
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(port) = self.port() {
            SocketAddr::new(self.ip_addr(), port.get()).fmt(f)
        } else {
            match self.ip_addr() {
                IpAddr::V4(ip) => ip.fmt(f),
                IpAddr::V6(ip) => write!(f, "[{ip}]"),
            }
        }
    }
}

impl From<IpAddr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: IpAddr) -> Self {
        Self::new(ip_addr, None)
    }
}

impl From<Ipv4Addr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: Ipv4Addr) -> Self {
        Self::new(IpAddr::from(ip_addr), None)
    }
}

impl From<Ipv6Addr> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr: Ipv6Addr) -> Self {
        Self::new(IpAddr::from(ip_addr), None)
    }
}

impl From<IpAddrWithPort> for IpAddr {
    #[inline]
    fn from(ip_addr_with_port: IpAddrWithPort) -> Self {
        ip_addr_with_port.ip_addr()
    }
}

impl From<SocketAddr> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddr) -> Self {
        Self::new(socket_addr.ip(), NonZeroU16::new(socket_addr.port()))
    }
}

impl From<SocketAddrV4> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddrV4) -> Self {
        SocketAddr::from(socket_addr).into()
    }
}

impl From<SocketAddrV6> for IpAddrWithPort {
    #[inline]
    fn from(socket_addr: SocketAddrV6) -> Self {
        SocketAddr::from(socket_addr).into()
    }
}

impl From<(IpAddr, u16)> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr_with_port: (IpAddr, u16)) -> Self {
        Self::new(ip_addr_with_port.0, NonZeroU16::new(ip_addr_with_port.1))
    }
}

impl From<(IpAddr, Option<NonZeroU16>)> for IpAddrWithPort {
    #[inline]
    fn from(ip_addr_with_port: (IpAddr, Option<NonZeroU16>)) -> Self {
        Self::new(ip_addr_with_port.0, ip_addr_with_port.1)
    }
}

/// 解析 IP 地址和端口号错误
#[derive(Error, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum IpAddrWithPortParseError {
    /// 地址解析错误
    #[error("invalid ip address: {0}")]
    ParseError(#[from] AddrParseError),
}

impl FromStr for IpAddrWithPort {
    type Err = IpAddrWithPortParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parse_result: Result<SocketAddr, AddrParseError> = s.parse();
        if let Ok(socket_addr) = parse_result {
            return Ok(socket_addr.into());
        }
        let ip_addr: IpAddr = s.parse()?;
        Ok(ip_addr.into())
    }
}

/// 终端地址
///
/// 该类型是枚举类型,表示一个域名和端口号,或 IP 地址和端口号
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "ty")]
#[non_exhaustive]
pub enum Endpoint {
    /// 域名和端口号
    DomainWithPort(DomainWithPort),

    /// IP 地址和端口号
    IpAddrWithPort(IpAddrWithPort),
}

impl Endpoint {
    /// 基于域名创建终端地址
    #[inline]
    pub fn new_from_domain(domain: impl Into<String>) -> Self {
        Self::DomainWithPort(DomainWithPort {
            domain: domain.into().into_boxed_str(),
            port: None,
        })
    }

    /// 基于域名和端口号创建终端地址
    #[inline]
    pub fn new_from_domain_with_port(domain: impl Into<String>, port: u16) -> Self {
        Self::DomainWithPort(DomainWithPort {
            domain: domain.into().into_boxed_str(),
            port: NonZeroU16::new(port),
        })
    }

    /// 基于 IP 地址创建终端地址
    ///
    /// IP 地址可以是 IPv4 地址或 IPv6 地址
    #[inline]
    pub const fn new_from_ip_addr(ip_addr: IpAddr) -> Self {
        Self::IpAddrWithPort(IpAddrWithPort { ip_addr, port: None })
    }

    /// 基于套接字地址创建终端地址
    ///
    /// 套接字地址可以是 IPv4 地址加端口号,或 IPv6 地址加端口号
    #[inline]
    pub fn new_from_socket_addr(addr: SocketAddr) -> Self {
        Self::IpAddrWithPort(IpAddrWithPort {
            ip_addr: addr.ip(),
            port: NonZeroU16::new(addr.port()),
        })
    }

    /// 如果终端地址包含域名,则获得域名
    #[inline]
    pub fn domain(&self) -> Option<&str> {
        match self {
            Self::DomainWithPort(domain_with_port) => Some(domain_with_port.domain()),
            _ => None,
        }
    }

    /// 如果终端地址包含 IP 地址,则获得域名
    #[inline]
    pub fn ip_addr(&self) -> Option<IpAddr> {
        match self {
            Self::IpAddrWithPort(ip_addr_with_port) => Some(ip_addr_with_port.ip_addr()),
            _ => None,
        }
    }

    /// 获得端口号
    #[inline]
    pub fn port(&self) -> Option<NonZeroU16> {
        match self {
            Self::DomainWithPort(domain_with_port) => domain_with_port.port(),
            Self::IpAddrWithPort(ip_addr_with_port) => ip_addr_with_port.port(),
        }
    }
More examples
Hide additional examples
src/client/chooser/subnet.rs (line 174)
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    fn get_network_address(&self, addr: IpAddrWithPort) -> Subnet {
        let subnet = match addr.ip_addr() {
            IpAddr::V4(ipv4_addr) => {
                let ipv4_network_addr =
                    get_network_address_of_ipv4_addr(ipv4_addr, self.inner.ipv4_netmask_prefix_length);
                IpAddr::V4(ipv4_network_addr)
            }
            IpAddr::V6(ipv6_addr) => {
                let ipv6_network_addr =
                    get_network_address_of_ipv6_addr(ipv6_addr, self.inner.ipv6_netmask_prefix_length);
                IpAddr::V6(ipv6_network_addr)
            }
        };
        return Subnet(IpAddrWithPort::new(subnet, addr.port()));

        fn get_network_address_of_ipv4_addr(addr: Ipv4Addr, prefix: u8) -> Ipv4Addr {
            Ipv4Net::new(addr, prefix).unwrap().network()
        }

        fn get_network_address_of_ipv6_addr(addr: Ipv6Addr, prefix: u8) -> Ipv6Addr {
            Ipv6Net::new(addr, prefix).unwrap().network()
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Deserialize this value from the given Serde deserializer. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Creates a value from an iterator. Read more
The associated error which can be returned from parsing.
Parses a string s to return a value of this type. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts self into T using Into<T>. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Pipes by value. This is generally the method you want to use. Read more
Borrows self and passes that borrow into the pipe function. Read more
Mutably borrows self and passes that borrow into the pipe function. Read more
Borrows self, then passes self.borrow() into the pipe function. Read more
Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Borrows self, then passes self.as_ref() into the pipe function.
Mutably borrows self, then passes self.as_mut() into the pipe function.
Borrows self, then passes self.deref() into the pipe function.
Mutably borrows self, then passes self.deref_mut() into the pipe function.
Should always be Self
Immutable access to a value. Read more
Mutable access to a value. Read more
Immutable access to the Borrow<B> of a value. Read more
Mutable access to the BorrowMut<B> of a value. Read more
Immutable access to the AsRef<R> view of a value. Read more
Mutable access to the AsMut<R> view of a value. Read more
Immutable access to the Deref::Target of a value. Read more
Mutable access to the Deref::Target of a value. Read more
Calls .tap() only in debug builds, and is erased in release builds.
Calls .tap_mut() only in debug builds, and is erased in release builds.
Calls .tap_borrow() only in debug builds, and is erased in release builds.
Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Calls .tap_ref() only in debug builds, and is erased in release builds.
Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Calls .tap_deref() only in debug builds, and is erased in release builds.
Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
Attempts to convert self into T using TryInto<T>. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more