diff --git a/README.md b/README.md index 1702c63e33a758dc52695890317c55f483209124..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 --- a/README.md +++ b/README.md @@ -1,310 +0,0 @@ -# COA-VANDEWAETER -# TP1 - -src : https://moodle.univ-lille.fr/pluginfile.php/4461109/mod_resource/content/1/tp-01.html - -```bash -cargo init -cargo run -``` - -## 2. First programs - -#### 2.1.1. Hello world - -On écrit le code dans `src/main.rs` : - -```rs -fn main(){ - println!("Hello world\n"); -} -``` - -#### 2.1.2. Variable and formatted output - -```rs -fn main(){ - let x = 42; - println!("{x}"); - eprintln!("{:x}", x); -} -``` - -#### 2.1.3. Mutable variable, while loop - -```rs -fn main() { - let mut i = 1; - while i <= 10 { - println!("{}", i); - i += 1; - } -} -``` - -#### 2.1.4. Password check - -```rs -use std::io; - -fn main() { - let password = "password"; - - println!("Enter password:"); - let mut input = String::new(); - io::stdin().read_line(&mut input).expect("Failed to read line"); - - if input.trim() == password { - println!("Good"); - } else { - eprintln!("Wrong"); - } -} -``` - -### 2.2. Functions, user defined data types, pattern matching - -#### 2.2.1. Simple function - -```rs -/// Check an input for a predetermined secret password -/// -/// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. -pub fn check_password(input: &str) -> Result<(), ()> { - let password = "password"; - if input.trim() == password { - Ok(()) - } else { - Err(()) - } -} -``` - -#### 2.2.2. Pattern matching - -```rs -use std::io; - -/// Check an input for a predetermined secret password -/// -/// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. -pub fn check_password(input: &str) -> Result<(), ()> { - let password = "password"; - if input.trim() == password { - Ok(()) - } else { - Err(()) - } -} - -fn main() { - println!("Enter password:"); - let mut input = String::new(); - io::stdin().read_line(&mut input).expect("Failed to read line"); - - match check_password(&input) { - Ok(()) => println!("Good"), - Err(()) => eprintln!("Wrong"), - } -} -``` - -#### 2.2.3. Enumeration - -```rs -use std::io; - -pub enum PasswordError { - Empty, - Wrong -} - -/// Check an input for a predetermined secret password -/// -/// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. -pub fn check_password(input: &str) -> Result<(), PasswordError> { - let password = "password"; - let trimmed_input = input.trim(); - if trimmed_input.is_empty(){ - Err(PasswordError::Empty) - } else if trimmed_input.trim() == password { - Ok(()) - } else { - Err(PasswordError::Wrong) - } -} - -fn main() { - println!("Enter password:"); - let mut input = String::new(); - io::stdin().read_line(&mut input).expect("Failed to read line"); - - match check_password(&input) { - Ok(()) => println!("Good"), - Err(PasswordError::Wrong) => eprintln!("Error: Wrong password"), - Err(PasswordError::Empty) => eprintln!("Error: password is empty") - } -} -``` - -#### 2.2.4. Structured types - -```rs -use std::io; - -pub enum PasswordError { - Empty, - Wrong -} - -/// A type that can be used to check if a given input is a valid password -pub struct PasswordChecker { - secret: String, -} - -impl PasswordChecker { - pub fn new(secret: &str) -> Self { - Self {secret: secret.to_string()} - } - - pub fn check(&self, input: &str) -> Result<(), PasswordError> { - let trimmed_input = input.trim(); - if trimmed_input.is_empty(){ - Err(PasswordError::Empty) - } else if trimmed_input.trim() == self.secret{ - Ok(()) - } else { - Err(PasswordError::Wrong) - } - } -} - -fn main() { - println!("Enter password:"); - let mut input = String::new(); - io::stdin().read_line(&mut input).expect("Failed to read line"); - - let checker = PasswordChecker::new("SuperSecret"); - - match checker.check(&input) { - Ok(()) => println!("Good"), - Err(PasswordError::Wrong) => eprintln!("Error: Wrong password"), - Err(PasswordError::Empty) => eprintln!("Error: password is empty") - } -} -``` - -## 3. More use of standard library and error handling - -### 3.1. Reading file and parsing strings - -On reprend la logique des exercices précédents pour récupérer le mot de passe mais cette fois pour adresses du fichier `ips.txt` qu'on ajoute à une liste - -```rs -/// Reads a file that contains an address per line and returns a vector with all well-formed -/// addresses while printing a warning on standard error for every malformed line. -/// -/// Addresses should be IPv4 or IPv6 addresses. -fn get_addrs(path: &str) -> Result<Vec<IpAddr>, std::io::Error> { - let contents = fs::read_to_string(path)?; - let mut addrs = Vec::new(); - for line in contents.lines() { - let trimmed = line.trim(); - if trimmed.is_empty() { - continue; - } - match trimmed.parse::<IpAddr>() { - Ok(addr) => addrs.push(addr), - Err(e) => eprintln!("'{}' is not a correct ip address: {}", trimmed, e), - } - } - Ok(addrs) -} -``` - -### 3.2. Network connection - -On essaie simplement de se connecter à une IP : - -```rs -/// Tries to connect to a given host with a TCP connection with a one second timeout. -/// -/// Returns `Ok(())` if the connection is successful, or a corresponding error if the connection fails. -fn try_connect(addr: IpAddr, port: u16) -> Result<(), std::io::Error> { - let socket_addr = SocketAddr::new(addr, port); - TcpStream::connect_timeout(&socket_addr, Duration::from_secs(1))?; - Ok(()) -} -``` - -### 3.3. Sample output - -Avec `ips.txt` : - -``` -127.0.0.1 -::1 -192.168.100.40 -Obviously malformed ligne - -10.0.278.1 -10.0.0.1 -``` - -Avec `src/main.rs` : - -```rs -use std::fs; -use std::net::{IpAddr, TcpStream, SocketAddr}; -use std::time::Duration; - -/// Reads a file that contains an address per line and returns a vector with all well-formed -/// addresses while printing a warning on standard error for every malformed line. -/// -/// Addresses should be IPv4 or IPv6 addresses. -fn get_addrs(path: &str) -> Result<Vec<IpAddr>, std::io::Error> { - let contents = fs::read_to_string(path)?; - let mut addrs = Vec::new(); - for line in contents.lines() { - let trimmed = line.trim(); - if trimmed.is_empty() { - continue; - } - match trimmed.parse::<IpAddr>() { - Ok(addr) => addrs.push(addr), - Err(e) => eprintln!("'{}' is not a correct ip address: {}", trimmed, e), - } - } - Ok(addrs) -} - -/// Tries to connect to a given host with a TCP connection with a one second timeout. -/// -/// Returns `Ok(())` if the connection is successful, or a corresponding error if the connection fails. -fn try_connect(addr: IpAddr, port: u16) -> Result<(), std::io::Error> { - let socket_addr = SocketAddr::new(addr, port); - TcpStream::connect_timeout(&socket_addr, Duration::from_secs(1))?; - Ok(()) -} - -fn main() { - println!("Parsing ips file"); - let addrs = match get_addrs("ips.txt") { - Ok(addrs) => addrs, - Err(e) => { - eprintln!("Error reading file: {}", e); - return; - } - }; - - for addr in addrs { - println!("Connecting to {}...", addr); - for port in &[22, 80, 443] { - match try_connect(addr, *port) { - Ok(()) => println!("\tport {} alive", port), - Err(e) => println!("\tport {} down ({})", port, e), - } - } - } -} -``` diff --git a/tp1/README.md b/tp1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a8cccf923787beaab32973f8e9e3202399532808 --- /dev/null +++ b/tp1/README.md @@ -0,0 +1,313 @@ +# COA-VANDEWAETER + +Dépôt : https://gitlab.univ-lille.fr/fabio.vandewaeter.etu/coa-vandewaeter + +# TP1 + +src : https://moodle.univ-lille.fr/pluginfile.php/4461109/mod_resource/content/1/tp-01.html + +```bash +cargo init +cargo run +``` + +## 2. First programs + +#### 2.1.1. Hello world + +On écrit le code dans `src/main.rs` : + +```rs +fn main(){ + println!("Hello world\n"); +} +``` + +#### 2.1.2. Variable and formatted output + +```rs +fn main(){ + let x = 42; + println!("{x}"); + eprintln!("{:x}", x); +} +``` + +#### 2.1.3. Mutable variable, while loop + +```rs +fn main() { + let mut i = 1; + while i <= 10 { + println!("{}", i); + i += 1; + } +} +``` + +#### 2.1.4. Password check + +```rs +use std::io; + +fn main() { + let password = "password"; + + println!("Enter password:"); + let mut input = String::new(); + io::stdin().read_line(&mut input).expect("Failed to read line"); + + if input.trim() == password { + println!("Good"); + } else { + eprintln!("Wrong"); + } +} +``` + +### 2.2. Functions, user defined data types, pattern matching + +#### 2.2.1. Simple function + +```rs +/// Check an input for a predetermined secret password +/// +/// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. +pub fn check_password(input: &str) -> Result<(), ()> { + let password = "password"; + if input.trim() == password { + Ok(()) + } else { + Err(()) + } +} +``` + +#### 2.2.2. Pattern matching + +```rs +use std::io; + +/// Check an input for a predetermined secret password +/// +/// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. +pub fn check_password(input: &str) -> Result<(), ()> { + let password = "password"; + if input.trim() == password { + Ok(()) + } else { + Err(()) + } +} + +fn main() { + println!("Enter password:"); + let mut input = String::new(); + io::stdin().read_line(&mut input).expect("Failed to read line"); + + match check_password(&input) { + Ok(()) => println!("Good"), + Err(()) => eprintln!("Wrong"), + } +} +``` + +#### 2.2.3. Enumeration + +```rs +use std::io; + +pub enum PasswordError { + Empty, + Wrong +} + +/// Check an input for a predetermined secret password +/// +/// Returns `Ok(())` if the input matches the password or `Err(())` otherwise. +pub fn check_password(input: &str) -> Result<(), PasswordError> { + let password = "password"; + let trimmed_input = input.trim(); + if trimmed_input.is_empty(){ + Err(PasswordError::Empty) + } else if trimmed_input.trim() == password { + Ok(()) + } else { + Err(PasswordError::Wrong) + } +} + +fn main() { + println!("Enter password:"); + let mut input = String::new(); + io::stdin().read_line(&mut input).expect("Failed to read line"); + + match check_password(&input) { + Ok(()) => println!("Good"), + Err(PasswordError::Wrong) => eprintln!("Error: Wrong password"), + Err(PasswordError::Empty) => eprintln!("Error: password is empty") + } +} +``` + +#### 2.2.4. Structured types + +```rs +use std::io; + +pub enum PasswordError { + Empty, + Wrong +} + +/// A type that can be used to check if a given input is a valid password +pub struct PasswordChecker { + secret: String, +} + +impl PasswordChecker { + pub fn new(secret: &str) -> Self { + Self {secret: secret.to_string()} + } + + pub fn check(&self, input: &str) -> Result<(), PasswordError> { + let trimmed_input = input.trim(); + if trimmed_input.is_empty(){ + Err(PasswordError::Empty) + } else if trimmed_input.trim() == self.secret{ + Ok(()) + } else { + Err(PasswordError::Wrong) + } + } +} + +fn main() { + println!("Enter password:"); + let mut input = String::new(); + io::stdin().read_line(&mut input).expect("Failed to read line"); + + let checker = PasswordChecker::new("SuperSecret"); + + match checker.check(&input) { + Ok(()) => println!("Good"), + Err(PasswordError::Wrong) => eprintln!("Error: Wrong password"), + Err(PasswordError::Empty) => eprintln!("Error: password is empty") + } +} +``` + +## 3. More use of standard library and error handling + +### 3.1. Reading file and parsing strings + +On reprend la logique des exercices précédents pour récupérer le mot de passe mais cette fois pour adresses du fichier `ips.txt` qu'on ajoute à une liste + +```rs +/// Reads a file that contains an address per line and returns a vector with all well-formed +/// addresses while printing a warning on standard error for every malformed line. +/// +/// Addresses should be IPv4 or IPv6 addresses. +fn get_addrs(path: &str) -> Result<Vec<IpAddr>, std::io::Error> { + let contents = fs::read_to_string(path)?; + let mut addrs = Vec::new(); + for line in contents.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + match trimmed.parse::<IpAddr>() { + Ok(addr) => addrs.push(addr), + Err(e) => eprintln!("'{}' is not a correct ip address: {}", trimmed, e), + } + } + Ok(addrs) +} +``` + +### 3.2. Network connection + +On essaie simplement de se connecter à une IP : + +```rs +/// Tries to connect to a given host with a TCP connection with a one second timeout. +/// +/// Returns `Ok(())` if the connection is successful, or a corresponding error if the connection fails. +fn try_connect(addr: IpAddr, port: u16) -> Result<(), std::io::Error> { + let socket_addr = SocketAddr::new(addr, port); + TcpStream::connect_timeout(&socket_addr, Duration::from_secs(1))?; + Ok(()) +} +``` + +### 3.3. Sample output + +Avec `ips.txt` : + +``` +127.0.0.1 +::1 +192.168.100.40 +Obviously malformed ligne + +10.0.278.1 +10.0.0.1 +``` + +Avec `src/main.rs` : + +```rs +use std::fs; +use std::net::{IpAddr, TcpStream, SocketAddr}; +use std::time::Duration; + +/// Reads a file that contains an address per line and returns a vector with all well-formed +/// addresses while printing a warning on standard error for every malformed line. +/// +/// Addresses should be IPv4 or IPv6 addresses. +fn get_addrs(path: &str) -> Result<Vec<IpAddr>, std::io::Error> { + let contents = fs::read_to_string(path)?; + let mut addrs = Vec::new(); + for line in contents.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + match trimmed.parse::<IpAddr>() { + Ok(addr) => addrs.push(addr), + Err(e) => eprintln!("'{}' is not a correct ip address: {}", trimmed, e), + } + } + Ok(addrs) +} + +/// Tries to connect to a given host with a TCP connection with a one second timeout. +/// +/// Returns `Ok(())` if the connection is successful, or a corresponding error if the connection fails. +fn try_connect(addr: IpAddr, port: u16) -> Result<(), std::io::Error> { + let socket_addr = SocketAddr::new(addr, port); + TcpStream::connect_timeout(&socket_addr, Duration::from_secs(1))?; + Ok(()) +} + +fn main() { + println!("Parsing ips file"); + let addrs = match get_addrs("ips.txt") { + Ok(addrs) => addrs, + Err(e) => { + eprintln!("Error reading file: {}", e); + return; + } + }; + + for addr in addrs { + println!("Connecting to {}...", addr); + for port in &[22, 80, 443] { + match try_connect(addr, *port) { + Ok(()) => println!("\tport {} alive", port), + Err(e) => println!("\tport {} down ({})", port, e), + } + } + } +} +```