Skip to content

Commit 264852d

Browse files
configure: set the interface address
Signed-off-by: Andy-Python-Programmer <[email protected]>
1 parent 3e26412 commit 264852d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/main.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ pub struct Ipv4Addr(pub [u8; ADDR_SIZE]);
2121

2222
impl Ipv4Addr {
2323
const EMPTY: Self = Self([0; ADDR_SIZE]);
24+
25+
fn as_u32(&self) -> u32 {
26+
byteorder::BigEndian::read_u32(&self.0)
27+
}
2428
}
2529

2630
impl Display for Ipv4Addr {
@@ -373,6 +377,43 @@ fn get_macaddress<'a>() -> &'a [u8; 6] {
373377
.expect("[ DHCPD ] (EE) failed to retrieve the mac address")
374378
}
375379

380+
fn configure(interface: &str, ip: Ipv4Addr) -> io::Result<()> {
381+
let fd = cvt(unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) })?;
382+
let socket = libc::sockaddr_in {
383+
sin_family: libc::AF_INET as _,
384+
sin_addr: libc::in_addr {
385+
s_addr: ip.as_u32(),
386+
},
387+
388+
sin_port: 0,
389+
sin_zero: [0; 8],
390+
};
391+
392+
let mut ifr: libc::ifreq = unsafe { core::mem::zeroed() };
393+
assert!(interface.len() <= libc::IFNAMSIZ);
394+
395+
// SAFETY: We have verified above that the name will fit
396+
// in the buffer.
397+
unsafe {
398+
core::ptr::copy_nonoverlapping(
399+
interface.as_ptr(),
400+
ifr.ifr_name.as_mut_ptr() as *mut u8,
401+
interface.len(),
402+
);
403+
}
404+
405+
ifr.ifr_ifru.ifru_addr = unsafe { *(&socket as *const _ as *const libc::sockaddr) };
406+
407+
// Set the interface address.
408+
unsafe {
409+
cvt(libc::ioctl(fd, libc::SIOCSIFADDR, &ifr))?;
410+
}
411+
412+
Ok(())
413+
}
414+
415+
const DEFAULT_NIC: &str = "eth0"; // FIXME: retrieve the default NIC from the kernel
416+
376417
pub fn main() -> Result<(), Box<dyn Error>> {
377418
let socket = UdpSocket::bind(("0.0.0.0", 68))?;
378419
socket.connect(("255.255.255.255", 67))?;
@@ -425,6 +466,8 @@ pub fn main() -> Result<(), Box<dyn Error>> {
425466
let subnet_mask = subnet_mask.unwrap();
426467
let dns = dns.unwrap();
427468

469+
configure(DEFAULT_NIC, ack.your_ip)?;
470+
428471
println!("[ DHCPD ] (!!) Configured:");
429472
println!("[ DHCPD ] (!!) IP: {}", ack.your_ip);
430473
println!("[ DHCPD ] (!!) Default Gateway: {}", default_gateway);

0 commit comments

Comments
 (0)