Commit ad201c61 authored by Ignamarte's avatar Ignamarte

Add generic Ipv4 object

parent cda26034
...@@ -3,7 +3,7 @@ name := "sipam" ...@@ -3,7 +3,7 @@ name := "sipam"
version := "0.1" version := "0.1"
scalaVersion := "2.13.1" scalaVersion := "2.13.1"
libraryDependencies += "commons-net" % "commons-net" % "3.6"
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.8.1" libraryDependencies += "com.typesafe.play" %% "play-json" % "2.8.1"
libraryDependencies += "com.github.pureconfig" %% "pureconfig" % "0.12.2" libraryDependencies += "com.github.pureconfig" %% "pureconfig" % "0.12.2"
libraryDependencies += "com.lihaoyi" %% "requests" % "0.4.6" libraryDependencies += "com.lihaoyi" %% "requests" % "0.4.6"
......
package api.objects package api.objects
import api.Client import api.Client
import org.apache.commons.net.util.SubnetUtils
import play.api.libs.json.{Json, Reads} import play.api.libs.json.{Json, Reads}
import utils.types.Ipv4
/** /**
...@@ -23,7 +25,12 @@ case class Subnet( ...@@ -23,7 +25,12 @@ case class Subnet(
description: Option[String], description: Option[String],
masterSubnetId: String, masterSubnetId: String,
vlanId: Option[String], vlanId: Option[String],
) ) {
private lazy val subnetUtil = new SubnetUtils(f"$subnet/$mask")
lazy val lowAddresses: Ipv4 = Ipv4.fromString(subnetUtil.getInfo.getLowAddress)
lazy val highAddresses: Ipv4 = Ipv4.fromString(subnetUtil.getInfo.getHighAddress)
lazy val allAddresses: Array[Ipv4] = subnetUtil.getInfo.getAllAddresses.map(Ipv4.fromString)
}
/** /**
......
package utils.types
/**
* An IPv4.
*
* @param _1 The first byte of the address
* @param _2 The second byte of the address
* @param _3 The third byte of the address
* @param _4 The last byte of the address
*/
class Ipv4(_1: Int, _2: Int, _3: Int, _4: Int) {
override def toString: String = f"IP: ${_1}.${_2}.${_3}.${_4}"
}
object Ipv4 {
/**
* Parse a string and return an `Ipv4`.
*
* @param ipStr The ip as a string. ex: 10.0.0.1
* @return An Ipv4 Object
*/
def fromString(ipStr: String): Ipv4 = {
val ip = ipStr.split("\\.").map(_.toInt)
val msg = f"The IP \'$ip\' is not a valid IPv4 address."
// Check IP validity
require(ip.length == 4, msg)
ip.foreach( n => if (n < 0 || n > 255) throw new IllegalArgumentException(msg))
new Ipv4(ip(0),ip(1),ip(2),ip(3))
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment