Java programming implements the method of traversing all macs between two MAC addresses

  • 2020-04-01 04:23:09
  • OfStack

This article illustrates a Java programming method for traversing all macs between two MAC addresses. Share with you for your reference, as follows:

In background management of issued devices, the device MAC field is often used to identify a unique device. However, when storing MAC addresses in bulk in the database, it is inevitable that the operation will be complicated if the method of adding parsed text line by line, and the MAC address text needs to be generated in advance. In fact, MAC addresses are incremented in hexadecimal order, so it is possible to enumerate all MAC addresses by giving only one interval. The following is a function I encapsulated that enumerates all macs in an interval by two MAC addresses.


 
public static void countBetweenMac(String macStart, String macEnd){ 
  long start = turnMacToLong(macStart); 
  long end = turnMacToLong(macEnd); 
  String prefix = macStart.substring(0,9); 
  String hex = null; 
  String suffix = null; 
  StringBuffer sb = null; 
  for(long i=start; i< end +1; i++){ 
   hex = Long.toHexString(i); 
   suffix = hex.substring(hex.length()-6); 
   sb = new StringBuffer(suffix); 
   sb.insert(2, ":"); 
   sb.insert(5, ":"); 
   System.out.println(prefix + sb.toString()); 
  } 
}
 
public static long turnMacToLong(String MAC){ 
  String hex = MAC.replaceAll("\:", ""); 
  long longMac = Long.parseLong(hex, 16); 
  return longMac; 
}

In addition, calculate the number function in MAC between two macs:


 
public static long countMac1(String macStart, String macEnd){ 
  String hexStart = macStart.replaceAll("\:", ""); 
  String hexEnd = macEnd.replaceAll("\:", ""); 
  long start = Long.parseLong(hexStart, 16); 
  long end = Long.parseLong(hexEnd, 16); 
  return end-start+1; 
}
 
public static long countMac(String macStart, String macEnd){ 
  String[] start = macStart.split("\:"); 
  String[] end = macEnd.split("\:"); 
  int x,y,z; 
  int a,b,c; 
  x = Integer.parseInt(start[3],16); 
  y = Integer.parseInt(start[4],16); 
  z = Integer.parseInt(start[5],16); 
  a = Integer.parseInt(end[3],16); 
  b = Integer.parseInt(end[4],16); 
  c = Integer.parseInt(end[5],16); 
  return (a-x)*16*16*16 + (b-y)*16*16 + c-z+1; 
}

I hope this article has been helpful to you in Java programming.


Related articles: