1 19 package org.objectweb.carol.cmi; 20 21 import java.lang.reflect.Method ; 22 import java.net.InetAddress ; 23 import java.net.UnknownHostException ; 24 import java.util.Enumeration ; 25 import java.util.LinkedList ; 26 27 31 public class InetMask { 32 byte[] bits; 33 int mask; 34 35 39 public InetMask(String textual) throws UnknownHostException { 40 int i = textual.indexOf('/'); 41 String ip = null; 42 if (i < 0) { 43 InetAddress a = InetAddress.getByName(ip); 44 bits = a.getAddress(); 45 mask = bits.length * 8; 46 } else { 47 ip = textual.substring(0, i); 48 mask = Integer.parseInt(textual.substring(i + 1)); 49 InetAddress a = InetAddress.getByName(ip); 50 bits = a.getAddress(); 51 } 52 } 53 54 public boolean match(InetAddress a) { 55 byte[] b = a.getAddress(); 56 int l = b.length; 57 if (l != bits.length) return false; 58 int m = mask; 59 for (int i=0; i<l; i++) { 60 if (m < 8) { 61 int v1 = b[i]; 62 if (v1 < 0) v1 += 256; 63 int v2 = bits[i]; 64 if (v2 < 0) v2 += 256; 65 int shift = 8 - m; 66 return (v1 >> shift) == (v2 >> shift); 67 } 68 m -= 8; 69 if (b[i] != bits[i]) return false; 70 } 71 return false; 72 } 73 74 78 public LinkedList filterLocal() { 79 LinkedList l = new LinkedList (); 80 try { 81 Enumeration en; 82 Class cl; 83 Object [] obj0 = { 84 }; 85 cl = Class.forName("java.net.NetworkInterface"); 86 Method meth = cl.getMethod("getNetworkInterfaces", new Class [0]); 87 Method getInet = cl.getMethod("getInetAddresses", new Class [0]); 88 en = (Enumeration ) meth.invoke(cl, obj0); 89 while (en.hasMoreElements()) { 90 Object o = en.nextElement(); 91 Enumeration enum2 = (Enumeration ) getInet.invoke(o, obj0); 92 while (enum2.hasMoreElements()) { 93 InetAddress a = (InetAddress ) enum2.nextElement(); 94 if (match(a)) { 95 l.add(a); 96 } 97 } 98 } 99 } catch (Exception e) { 100 if (l.isEmpty()) { 101 return l; 102 } else { 103 return new LinkedList (); 104 } 105 } 106 return l; 107 } 108 } 109 | Popular Tags |