Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fmt;
- struct Address {
- ip: Vec<u8>,
- mask: Vec<u8>,
- }
- impl Address {
- fn vec_to_binary(vector: &Vec<u8>) -> String {
- let mut result = String::new();
- for i in vector {
- let mut value = String::new();
- value = format!("{:b}",i);
- while value.len() < 8 {
- value = format!("{}{}", "0", &value);
- }
- result += &value;
- }
- return result;
- }
- fn bytes_and(a: String, b: String) -> String {
- let mut result = String::new();
- let mut a = a.chars();
- let mut b = b.chars();
- let zero = "0".chars().nth(0).unwrap();
- let one = "1".chars().nth(0).unwrap();
- for _i in 0..32 {
- let temp_a = a.next().unwrap();
- let temp_b = b.next().unwrap();
- if (temp_a == one) && (temp_b == one) {
- result += "1";
- } else {
- result += "0";
- }
- }
- return result;
- }
- fn cidr(&self) -> String {
- let cidr = Address::vec_to_binary(&self.mask);
- return format!("{}", cidr.matches("1").count());
- }
- fn subnet_address(&self) -> String {
- let mask = Address::vec_to_binary(&self.mask);
- let ip = Address::vec_to_binary(&self.ip);
- let subnet = Address::bytes_and(ip, mask);
- return subnet;
- }
- }
- impl fmt::Display for Address {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let str_ip = format!("{}.{}.{}.{}", self.ip[0], self.ip[1], self.ip[2], self.ip[3]);
- write!(f, "{}/{}", str_ip, &self.cidr())
- }
- }
- fn main() {
- let ip = vec!(192,168,0,1);
- let mask = vec!(255,255,255,0);
- let address = Address { ip, mask };
- println!("{}", address.subnet_address());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement