Struct qiniu_http_client::IpAddrWithPort
source · pub struct IpAddrWithPort { /* private fields */ }
Expand description
IP 地址和端口号
用来表示一个七牛服务器的地址,端口号是可选的,如果不提供,则根据传输协议判定默认的端口号。
Implementations§
source§impl IpAddrWithPort
impl IpAddrWithPort
sourcepub const fn new(ip_addr: IpAddr, port: Option<NonZeroU16>) -> Self
pub const fn new(ip_addr: IpAddr, port: Option<NonZeroU16>) -> Self
创建 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
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)
}
}
sourcepub const fn ip_addr(&self) -> IpAddr
pub const fn ip_addr(&self) -> IpAddr
获取 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
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))
}
sourcepub const fn port(&self) -> Option<NonZeroU16>
pub const fn port(&self) -> Option<NonZeroU16>
获取端口号
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
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§
source§impl Clone for IpAddrWithPort
impl Clone for IpAddrWithPort
source§fn clone(&self) -> IpAddrWithPort
fn clone(&self) -> IpAddrWithPort
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl Debug for IpAddrWithPort
impl Debug for IpAddrWithPort
source§impl<'de> Deserialize<'de> for IpAddrWithPort
impl<'de> Deserialize<'de> for IpAddrWithPort
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl Display for IpAddrWithPort
impl Display for IpAddrWithPort
source§impl From<(IpAddr, Option<NonZeroU16>)> for IpAddrWithPort
impl From<(IpAddr, Option<NonZeroU16>)> for IpAddrWithPort
source§impl From<IpAddr> for IpAddrWithPort
impl From<IpAddr> for IpAddrWithPort
source§impl From<IpAddrWithPort> for Endpoint
impl From<IpAddrWithPort> for Endpoint
source§fn from(ip_addr_with_port: IpAddrWithPort) -> Self
fn from(ip_addr_with_port: IpAddrWithPort) -> Self
Converts to this type from the input type.
source§impl From<IpAddrWithPort> for IpAddr
impl From<IpAddrWithPort> for IpAddr
source§fn from(ip_addr_with_port: IpAddrWithPort) -> Self
fn from(ip_addr_with_port: IpAddrWithPort) -> Self
Converts to this type from the input type.
source§impl From<Ipv4Addr> for IpAddrWithPort
impl From<Ipv4Addr> for IpAddrWithPort
source§impl From<Ipv6Addr> for IpAddrWithPort
impl From<Ipv6Addr> for IpAddrWithPort
source§impl From<SocketAddr> for IpAddrWithPort
impl From<SocketAddr> for IpAddrWithPort
source§fn from(socket_addr: SocketAddr) -> Self
fn from(socket_addr: SocketAddr) -> Self
Converts to this type from the input type.
source§impl From<SocketAddrV4> for IpAddrWithPort
impl From<SocketAddrV4> for IpAddrWithPort
source§fn from(socket_addr: SocketAddrV4) -> Self
fn from(socket_addr: SocketAddrV4) -> Self
Converts to this type from the input type.
source§impl From<SocketAddrV6> for IpAddrWithPort
impl From<SocketAddrV6> for IpAddrWithPort
source§fn from(socket_addr: SocketAddrV6) -> Self
fn from(socket_addr: SocketAddrV6) -> Self
Converts to this type from the input type.
source§impl FromIterator<IpAddrWithPort> for ChosenResults
impl FromIterator<IpAddrWithPort> for ChosenResults
source§fn from_iter<T: IntoIterator<Item = IpAddrWithPort>>(iter: T) -> Self
fn from_iter<T: IntoIterator<Item = IpAddrWithPort>>(iter: T) -> Self
Creates a value from an iterator. Read more
source§impl FromStr for IpAddrWithPort
impl FromStr for IpAddrWithPort
source§impl Hash for IpAddrWithPort
impl Hash for IpAddrWithPort
source§impl PartialEq<IpAddrWithPort> for IpAddrWithPort
impl PartialEq<IpAddrWithPort> for IpAddrWithPort
source§fn eq(&self, other: &IpAddrWithPort) -> bool
fn eq(&self, other: &IpAddrWithPort) -> bool
This method tests for
self
and other
values to be equal, and is used
by ==
.source§impl Serialize for IpAddrWithPort
impl Serialize for IpAddrWithPort
impl Copy for IpAddrWithPort
impl Eq for IpAddrWithPort
impl StructuralEq for IpAddrWithPort
impl StructuralPartialEq for IpAddrWithPort
Auto Trait Implementations§
impl RefUnwindSafe for IpAddrWithPort
impl Send for IpAddrWithPort
impl Sync for IpAddrWithPort
impl Unpin for IpAddrWithPort
impl UnwindSafe for IpAddrWithPort
Blanket Implementations§
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key
and return true
if they are equal.source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Pipes by value. This is generally the method you want to use. Read more
source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
Borrows
self
and passes that borrow into the pipe function. Read moresource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
Mutably borrows
self
and passes that borrow into the pipe function. Read moresource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
Borrows
self
, then passes self.as_ref()
into the pipe function.source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
Mutably borrows
self
, then passes self.as_mut()
into the pipe
function.source§impl<T> Tap for T
impl<T> Tap for T
source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
Immutable access to the
Borrow<B>
of a value. Read moresource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
Mutable access to the
BorrowMut<B>
of a value. Read moresource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
Immutable access to the
AsRef<R>
view of a value. Read moresource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
Mutable access to the
AsMut<R>
view of a value. Read moresource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
Immutable access to the
Deref::Target
of a value. Read moresource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
Mutable access to the
Deref::Target
of a value. Read moresource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
Calls
.tap()
only in debug builds, and is erased in release builds.source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
Calls
.tap_mut()
only in debug builds, and is erased in release
builds.source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
Calls
.tap_borrow()
only in debug builds, and is erased in release
builds.source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
Calls
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
Calls
.tap_ref()
only in debug builds, and is erased in release
builds.source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
Calls
.tap_ref_mut()
only in debug builds, and is erased in release
builds.