1 22 23 package caramel.util; 24 25 import java.net.*; 26 import houston.*; 27 28 public class NetUtils 29 { 30 33 private static String _localHostName = null; 34 35 public static char getIpClass( InetAddress ip ) 36 { 37 40 byte address[] = ip.getAddress(); 41 if( address.length != 4 ) 42 throw new IllegalArgumentException ( "address has more than 4 bytes; possibly IPv6 address" ); 43 44 int firstByte = address[0]; 45 if( ( firstByte & 0x80 ) == 0 ) 46 return 'A'; 47 else if( ( firstByte & 0xC0 ) == 0x80 ) 48 return 'B'; 49 else if( ( firstByte & 0xE0 ) == 0xC0 ) 50 return 'C'; 51 else if( ( firstByte & 0xF0 ) == 0xE0 ) 52 return 'D'; 53 else if( ( firstByte & 0xF8 ) == 0xF0 ) 54 return 'E'; 55 else 56 return 'F'; 57 } 58 59 public static String getLocalHostName() 60 { 61 if( _localHostName == null ) 62 { 63 try 64 { 65 _localHostName = InetAddress.getLocalHost().getHostName(); 66 } 67 catch( UnknownHostException e ) 68 { 69 Status.error( "*** failed to get local host name: " + e.toString() ); 70 _localHostName = "127.0.0.1"; 72 } 73 } 74 75 return _localHostName; 76 } 77 78 public static boolean isHostName( String host ) 79 { 80 83 char s[] = host.toCharArray(); 84 87 for( int i = 0; i < s.length; i++ ) 88 { 89 if( !Character.isDigit( s[i] ) && s[i] != '.' ) 90 return true; 91 } 92 return false; 93 } 94 95 public static boolean isLoopbackIp( InetAddress ip ) 96 { 97 byte address[] = ip.getAddress(); 98 99 if( address[0] == 127 100 && address[1] == 0 101 && address[2] == 0 102 && address[3] == 1 ) 103 return true; 104 105 return false; 106 } 107 108 public static boolean isPrivateIp( InetAddress ip ) 109 { 110 116 byte address[] = ip.getAddress(); 117 118 int firstQuad = address[0] < 0 ? address[0] + 256 : address[0]; 122 int secondQuad = address[1] < 0 ? address[1] + 256 : address[1]; 123 int thirdQuad = address[2] < 0 ? address[2] + 256 : address[2]; 124 int fourthQuad = address[3] < 0 ? address[3] + 256 : address[3]; 125 126 if( firstQuad == 10 ) 128 return true; 129 130 if( firstQuad == 172 ) 132 { 133 if( secondQuad >= 16 && secondQuad <= 31 ) 134 return true; 135 } 136 137 if( firstQuad == 192 && secondQuad == 168 ) 139 return true; 140 141 return false; 142 } 143 144 } 145 | Popular Tags |