Compare commits
3 Commits
247587d99b
...
f2ad0de89b
Author | SHA1 | Date | |
---|---|---|---|
f2ad0de89b | |||
43cd0f5bc5 | |||
d5ec71a000 |
20
src/main.rs
20
src/main.rs
@ -1,5 +1,23 @@
|
||||
use std::{io, str::FromStr};
|
||||
|
||||
mod networking;
|
||||
use networking::ip::{IpAddr};
|
||||
|
||||
fn main() {
|
||||
println!("Hello, World!")
|
||||
println!("Enter the IP and CIDR for your given network");
|
||||
|
||||
loop {
|
||||
let mut ip = String::new();
|
||||
io::stdin().read_line(&mut ip).unwrap();
|
||||
let ip_address = match IpAddr::from_str(x) {
|
||||
Err(_) => {
|
||||
println!("fucked it");
|
||||
IpAddr::V4(0, 0, 0, 0)
|
||||
},
|
||||
Ok(ip) => ip,
|
||||
};
|
||||
|
||||
println!("you entered, {:?}", ip_address);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,5 +1,8 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct InvalidIPErr;
|
||||
|
||||
/// Ip address enum that includes associated type
|
||||
///
|
||||
/// # Example
|
||||
@ -15,9 +18,6 @@ pub enum IpAddr {
|
||||
V6(String)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct InvalidIPErr;
|
||||
|
||||
impl ToString for IpAddr {
|
||||
/// Function that returns an IP address in string form
|
||||
fn to_string(&self) -> String {
|
||||
@ -32,6 +32,16 @@ impl ToString for IpAddr {
|
||||
impl FromStr for IpAddr {
|
||||
type Err = InvalidIPErr;
|
||||
/// Function that generates a IpAddr / Err from a string
|
||||
///
|
||||
/// # Limitation
|
||||
/// Currently only works for IPs of type IPv4
|
||||
/// # Example
|
||||
/// ```
|
||||
/// let ip: &str = "127.0.0.1";
|
||||
///
|
||||
/// let parsed_ip: IpAddr = IpAddr::from_str(ip);
|
||||
/// ///parsed_ip = IpAddr::V4(127,0,0,1)
|
||||
/// ```
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let split_ip = s.split('.');
|
||||
if split_ip.clone().count() != 4 {
|
||||
@ -41,6 +51,10 @@ impl FromStr for IpAddr {
|
||||
let mut ip: [u8; 4] = Default::default();
|
||||
//Go through each octet and ensure it can be parsed;
|
||||
for (i, oct) in split_ip.into_iter().enumerate() {
|
||||
if i > ip.len() {
|
||||
//Ip string is out of the range of the 4 octets in an IPv4 Address
|
||||
return Err(InvalidIPErr)
|
||||
}
|
||||
match oct.parse::<u8>() {
|
||||
Ok(parsed_oct) => ip[i] = parsed_oct,
|
||||
Err(_) => return Err(InvalidIPErr)
|
||||
@ -86,9 +100,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
///Tests if an invalid Ip will cause a panic when
|
||||
/// converting from a string to an IpAddr
|
||||
fn invalid_string_to_ip() {
|
||||
use super::*;
|
||||
let ip = "Hello, world";
|
||||
let ip = "127.0.0.0.1";
|
||||
IpAddr::from_str(ip).unwrap();
|
||||
assert_eq!(IpAddr::from_str(ip), Err(InvalidIPErr))
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
mod ip;
|
||||
pub mod ip;
|
||||
use ip::IpAddr;
|
||||
|
||||
#[allow(unused)]
|
||||
|
Loading…
x
Reference in New Issue
Block a user