skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Tuesday, October 16, 2012

Function to Check IpAddress is within a Specified Range

Posted by Raju Gupta at 3:00 PM – 0 comments
 
The code snippet is used to check the IpAddress given is within a specified range. It will set the inRange boolean to true if IpAddress is within that range.

/**
  * @param args
  * @throws UnknownHostException 
  */
 public static void main(String[] args){
  // TODO Auto-generated method stub
  
  //Pass the IpAdress to check whether it is in the Specified Range
  String ipAddress = "";
  //IpAddress Ranges are to be Specified here.
  String ipAddressRange = "";
  boolean inRange = false;
  if (!ipAddressRange.isEmpty()){
   String[] addressRanges = ipAddressRange.split(",");
   for (String ipAddr:addressRanges){
    String[] ipAddrLowHigh = ipAddr.split("-");
    try {
     long ipAddrLower = ipToLong(InetAddress.getByName(ipAddrLowHigh[0]));         
     long ipAddrHigher = ipToLong(InetAddress.getByName(ipAddrLowHigh[1]));         
     long ipAddrToTest = ipToLong(InetAddress.getByName(ipAddress));  
     inRange = ipAddrToTest >= ipAddrLower && ipAddrToTest <= ipAddrHigher;
     System.out.println("True = If Ipaddress is within the range:::::"+inRange);
     if (inRange){
      break;
     }
    } catch (UnknownHostException ex){
     System.out.println("UnknownHostException Occurred in IFAUtils.isIpAddressRange:::"+ex.getMessage());
     ex.printStackTrace();
    }
   } 
  } 
 } 
 
 /**
  * Method ipToLong. converting ipAddress to Long value for given ipAddress is in available range.
  * @param ipAddress contains the System ipAddress. 
  * @return long return converted long value will return.
  */
 public static long ipToLong(InetAddress ipAddress) {         
  byte[] octets = ipAddress.getAddress();         
  long result = 0;         
  for (byte octet : octets) {             
   result <<= 8;             
   result |= octet & 0xff;         
  }         
  return result;     
 }  



Labels: Java Network Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger