Skip to content

Commit 780632e

Browse files
committed
Add cmd module
This module implements basic "ip" commands to add and remove IP addresses on network interfaces and to bring interfaces up before use.
1 parent 07c3a30 commit 780632e

File tree

3 files changed

+64
-1
lines changed

3 files changed

+64
-1
lines changed

crates/lib-dhcp/src/client/cmd.rs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
use std::{
2+
net::Ipv4Addr,
3+
process::{Command, ExitStatus},
4+
};
5+
6+
use thiserror::Error;
7+
8+
#[derive(Debug, Error)]
9+
pub enum CmdError {
10+
#[error("Unexpected exist status: {0}")]
11+
UnexpectedStatus(ExitStatus),
12+
13+
#[error("IO error: {0}")]
14+
IoError(#[from] std::io::Error),
15+
}
16+
17+
pub fn set_interface_up(interface_name: &String) -> Result<(), CmdError> {
18+
let status = Command::new("ip")
19+
.args(["link", "set"])
20+
.args(["dev", interface_name, "up"])
21+
.status()?;
22+
23+
if !status.success() {
24+
return Err(CmdError::UnexpectedStatus(status));
25+
}
26+
27+
Ok(())
28+
}
29+
30+
/// Flushes the IP address of the interface with `interface_name`.
31+
pub fn flush_ip_address(interface_name: &String) -> Result<(), CmdError> {
32+
// ip -4 addr flush dev ${interface}
33+
let status = Command::new("ip")
34+
.arg("-4")
35+
.args(["addr", "flush"])
36+
.args(["dev", interface_name])
37+
.status()?;
38+
39+
if !status.success() {
40+
return Err(CmdError::UnexpectedStatus(status));
41+
}
42+
43+
Ok(())
44+
}
45+
46+
/// Adds an IP address to the interface with `interface_name`.
47+
pub fn add_ip_address(ip_addr: &Ipv4Addr, interface_name: &String) -> Result<(), CmdError> {
48+
let status = Command::new("ip")
49+
.arg("-4")
50+
.args(["addr", "add", &ip_addr.to_string()])
51+
.args(["dev", interface_name])
52+
.status()?;
53+
54+
if !status.success() {
55+
return Err(CmdError::UnexpectedStatus(status));
56+
}
57+
58+
Ok(())
59+
}

crates/lib-dhcp/src/client/error.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use network_interface::Error as InterfaceError;
44
use thiserror::Error;
55

66
use crate::{
7-
client::state::DhcpStateError,
7+
client::{cmd::CmdError, state::DhcpStateError},
88
types::{MessageError, ParseHardwareAddrError},
99
};
1010

@@ -34,6 +34,9 @@ pub enum ClientError {
3434
#[error("Message error: {0}")]
3535
MessageError(#[from] MessageError),
3636

37+
#[error("Command error: {0}")]
38+
CmdError(#[from] CmdError),
39+
3740
#[error("Invalid message format or length: {0}")]
3841
Invalid(String),
3942
}

crates/lib-dhcp/src/client/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use crate::{
2020
utils, TimeoutResult, DHCP_MINIMUM_LEGAL_MAX_MESSAGE_SIZE, DHCP_SERVER_PORT,
2121
};
2222

23+
mod cmd;
2324
mod error;
2425
mod state;
2526

0 commit comments

Comments
 (0)