nu_command/network/
port.rs1use nu_engine::command_prelude::*;
2use nu_protocol::shell_error::io::IoError;
3
4use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
5
6#[derive(Clone)]
7pub struct Port;
8
9impl Command for Port {
10 fn name(&self) -> &str {
11 "port"
12 }
13
14 fn signature(&self) -> Signature {
15 Signature::build("port")
16 .input_output_types(vec![(Type::Nothing, Type::Int)])
17 .optional(
18 "start",
19 SyntaxShape::Int,
20 "The start port to scan (inclusive).",
21 )
22 .optional("end", SyntaxShape::Int, "The end port to scan (inclusive).")
23 .category(Category::Network)
24 }
25
26 fn description(&self) -> &str {
27 "Get a free port from system."
28 }
29
30 fn search_terms(&self) -> Vec<&str> {
31 vec!["network", "http"]
32 }
33
34 fn run(
35 &self,
36 engine_state: &EngineState,
37 stack: &mut Stack,
38 call: &Call,
39 _input: PipelineData,
40 ) -> Result<PipelineData, ShellError> {
41 get_free_port(engine_state, stack, call)
42 }
43
44 fn examples(&self) -> Vec<Example> {
45 vec![
46 Example {
47 description: "get a free port between 3121 and 4000",
48 example: "port 3121 4000",
49 result: Some(Value::test_int(3121)),
50 },
51 Example {
52 description: "get a free port from system",
53 example: "port",
54 result: None,
55 },
56 ]
57 }
58}
59
60fn get_free_port(
61 engine_state: &EngineState,
62 stack: &mut Stack,
63 call: &Call,
64) -> Result<PipelineData, ShellError> {
65 let from_io_error = IoError::factory(call.head, None);
66
67 let start_port: Option<Spanned<usize>> = call.opt(engine_state, stack, 0)?;
68 let end_port: Option<Spanned<usize>> = call.opt(engine_state, stack, 1)?;
69
70 let listener = if start_port.is_none() && end_port.is_none() {
71 TcpListener::bind("127.0.0.1:0").map_err(&from_io_error)?
73 } else {
74 let (start_port, start_span) = match start_port {
75 Some(p) => (p.item, Some(p.span)),
76 None => (1024, None),
77 };
78
79 let start_port = match u16::try_from(start_port) {
80 Ok(p) => p,
81 Err(e) => {
82 return Err(ShellError::CantConvert {
83 to_type: "u16".into(),
84 from_type: "usize".into(),
85 span: start_span.unwrap_or(call.head),
86 help: Some(format!("{e} (min: {}, max: {})", u16::MIN, u16::MAX)),
87 });
88 }
89 };
90
91 let (end_port, end_span) = match end_port {
92 Some(p) => (p.item, Some(p.span)),
93 None => (65535, None),
94 };
95
96 let end_port = match u16::try_from(end_port) {
97 Ok(p) => p,
98 Err(e) => {
99 return Err(ShellError::CantConvert {
100 to_type: "u16".into(),
101 from_type: "usize".into(),
102 span: end_span.unwrap_or(call.head),
103 help: Some(format!("{e} (min: {}, max: {})", u16::MIN, u16::MAX)),
104 });
105 }
106 };
107
108 let range_span = match (start_span, end_span) {
109 (Some(start), Some(end)) => Span::new(start.start, end.end),
110 (Some(start), None) => start,
111 (None, Some(end)) => end,
112 (None, None) => call.head,
113 };
114
115 if start_port > end_port {
117 return Err(ShellError::InvalidRange {
118 left_flank: start_port.to_string(),
119 right_flank: end_port.to_string(),
120 span: range_span,
121 });
122 }
123
124 'search: {
125 let mut last_err = None;
126 for port in start_port..=end_port {
127 let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port));
128 match TcpListener::bind(addr) {
129 Ok(listener) => break 'search Ok(listener),
130 Err(err) => last_err = Some(err),
131 }
132 }
133
134 Err(IoError::new_with_additional_context(
135 last_err.expect("range not empty, validated before"),
136 range_span,
137 None,
138 "Every port has been tried, but no valid one was found",
139 ))
140 }?
141 };
142
143 let free_port = listener.local_addr().map_err(&from_io_error)?.port();
144 Ok(Value::int(free_port as i64, call.head).into_pipeline_data())
145}