Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. use std::fmt;
  2.  
  3. struct Address {
  4. ip: Vec<u8>,
  5. mask: Vec<u8>,
  6. }
  7.  
  8. impl Address {
  9.  
  10. fn vec_to_binary(vector: &Vec<u8>) -> String {
  11. let mut result = String::new();
  12. for i in vector {
  13.  
  14. let mut value = String::new();
  15. value = format!("{:b}",i);
  16.  
  17. while value.len() < 8 {
  18. value = format!("{}{}", "0", &value);
  19. }
  20.  
  21. result += &value;
  22. }
  23.  
  24. return result;
  25. }
  26.  
  27. fn bytes_and(a: String, b: String) -> String {
  28. let mut result = String::new();
  29. let mut a = a.chars();
  30. let mut b = b.chars();
  31. let zero = "0".chars().nth(0).unwrap();
  32. let one = "1".chars().nth(0).unwrap();
  33.  
  34. for _i in 0..32 {
  35. let temp_a = a.next().unwrap();
  36. let temp_b = b.next().unwrap();
  37.  
  38.  
  39. if (temp_a == one) && (temp_b == one) {
  40. result += "1";
  41. } else {
  42. result += "0";
  43. }
  44.  
  45. }
  46. return result;
  47. }
  48.  
  49.  
  50. fn cidr(&self) -> String {
  51. let cidr = Address::vec_to_binary(&self.mask);
  52.  
  53. return format!("{}", cidr.matches("1").count());
  54. }
  55.  
  56.  
  57. fn subnet_address(&self) -> String {
  58. let mask = Address::vec_to_binary(&self.mask);
  59. let ip = Address::vec_to_binary(&self.ip);
  60. let subnet = Address::bytes_and(ip, mask);
  61.  
  62. return subnet;
  63. }
  64.  
  65. }
  66.  
  67. impl fmt::Display for Address {
  68. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  69. let str_ip = format!("{}.{}.{}.{}", self.ip[0], self.ip[1], self.ip[2], self.ip[3]);
  70.  
  71. write!(f, "{}/{}", str_ip, &self.cidr())
  72. }
  73.  
  74. }
  75.  
  76.  
  77.  
  78.  
  79. fn main() {
  80. let ip = vec!(192,168,0,1);
  81. let mask = vec!(255,255,255,0);
  82. let address = Address { ip, mask };
  83.  
  84. println!("{}", address.subnet_address());
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement