NiFi Groovy Script to Find 1st and Last IPs in Subnet

NiFi Groovy Script to Find 1st and Last IPs in Subnet

Takes a subnet cidr from a flowfile attribute called subnetCidr as shown below

and returns the first and last usable IP addresses as attributes

Add the below code into theĀ script body attribute of an ExecuteScript processor that is set to Groovy as the script engine.


import java.nio.charset.StandardCharsets
import org.apache.nifi.components.PropertyValue
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
flowFileList = session.get(1)
if(!flowFileList.isEmpty()) {
flowFileList.each { flowFile ->
subnetCidr = flowFile.getAttribute('subnetCidr')
def (ipAddress, subnetMask) = subnetCidr.split("/")
def ipInt = ipAddress.split("\\.").inject(0) { acc, value -> (acc << 8) + value.toInteger() }
def subnetMaskInt = (-1 << (32 - subnetMask.toInteger()))
def networkAddress = ipInt & subnetMaskInt
def broadcastAddress = networkAddress | ~subnetMaskInt
def firstUsableIp = ""
def lastUsableIp = ""
if(subnetMask != "31")
{
firstUsableIp = networkAddress + 1
lastUsableIp = broadcastAddress - 1
}
else
{
firstUsableIp = networkAddress
lastUsableIp = broadcastAddress
}
def availableIps = []
for (int i = firstUsableIp; i <= lastUsableIp; i++) { def octet1 = (i >> 24) & 0xff
def octet2 = (i >> 16) & 0xff
def octet3 = (i >> 8) & 0xff
def octet4 = i & 0xff
availableIps.add("$octet1.$octet2.$octet3.$octet4")
}
a = availableIps[0]
b = availableIps[(lastUsableIp-firstUsableIp)]
flowFile = session.putAttribute(flowFile, 'subnetMask', subnetMask)
flowFile = session.putAttribute(flowFile, 'firstUsableIp', a )
flowFile = session.putAttribute(flowFile, 'lastUsableIp', b)
session.transfer(flowFile, REL_SUCCESS)
}
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *