1 29 30 31 package snmp; 32 33 34 import java.util.*; 35 36 37 40 41 42 public class SNMPIPAddress extends SNMPOctetString 43 { 44 46 47 50 51 public SNMPIPAddress() 52 { 53 tag = SNMPBERCodec.SNMPIPADDRESS; 55 data = new byte[4]; 56 for (int i = 0; i < 4; i++) 57 data[i] = 0; 58 } 59 60 61 66 67 public SNMPIPAddress(String string) 68 throws SNMPBadValueException 69 { 70 tag = SNMPBERCodec.SNMPIPADDRESS; 71 this.data = parseIPAddress(string); 72 } 73 74 75 76 77 78 84 85 public SNMPIPAddress(byte[] enc) 86 throws SNMPBadValueException 87 { 88 89 tag = SNMPBERCodec.SNMPIPADDRESS; 90 91 if (enc.length == 4) 92 { 93 data = enc; 94 } 95 else { 97 throw new SNMPBadValueException(" IPAddress: bad BER encoding supplied to set value "); 98 } 99 } 100 101 102 103 104 105 110 111 public void setValue(Object newAddress) 112 throws SNMPBadValueException 113 { 114 if ((newAddress instanceof byte[]) && (((byte[])newAddress).length == 4)) 115 data = (byte[])newAddress; 116 else if (newAddress instanceof String ) 117 { 118 data = parseIPAddress((String )newAddress); 119 } 120 else 121 throw new SNMPBadValueException(" IPAddress: bad data supplied to set value "); 122 } 123 124 125 126 129 130 public String toString() 131 { 132 StringBuffer returnStringBuffer = new StringBuffer (); 133 134 if (data.length > 0) 135 { 136 int convert = data[0]; 137 if (convert < 0) 138 convert += 256; 139 returnStringBuffer.append(convert); 140 141 for (int i = 1; i < data.length; i++) 142 { 143 convert = data[i]; 144 if (convert < 0) 145 convert += 256; 146 returnStringBuffer.append("."); 147 returnStringBuffer.append(convert); 148 } 149 } 150 151 return returnStringBuffer.toString(); 152 } 153 154 155 156 157 private byte[] parseIPAddress(String addressString) 158 throws SNMPBadValueException 159 { 160 try 161 { 162 StringTokenizer st = new StringTokenizer(addressString, " ."); 163 int size = 0; 164 165 while (st.hasMoreTokens()) 166 { 167 size++; 169 st.nextToken(); 170 } 171 172 if (size != 4) 173 { 174 throw new SNMPBadValueException(" IPAddress: wrong number of components supplied to set value "); 175 } 176 177 byte[] returnBytes = new byte[size]; 178 179 st = new StringTokenizer(addressString, " ."); 180 181 for (int i = 0; i < size; i++) 182 { 183 int addressComponent = (Integer.parseInt(st.nextToken())); 184 if ((addressComponent < 0) || (addressComponent > 255)) 185 throw new SNMPBadValueException(" IPAddress: invalid component supplied to set value "); 186 returnBytes[i] = (byte)addressComponent; 187 } 188 189 return returnBytes; 190 191 } 192 catch (NumberFormatException e) 193 { 194 throw new SNMPBadValueException(" IPAddress: invalid component supplied to set value "); 195 } 196 197 } 198 199 200 201 202 } | Popular Tags |