Here you can find the source of textToNumericFormat(String src)
Parameter | Description |
---|---|
src | a String representing an IPv4 address in standard format |
public static byte[] textToNumericFormat(String src)
//package com.java2s; /* //from w w w. ja v a2 s . com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { public static final int INADDRSZ = 4; /** * Converts IPv4 address in its textual presentation form into its numeric binary form. * * @param src * a String representing an IPv4 address in standard format * @return a byte array representing the IPv4 numeric address */ public static byte[] textToNumericFormat(String src) { if (src == null || src.length() == 0) { return null; } int octets; char ch; byte[] dst = new byte[INADDRSZ]; char[] srcb = src.toCharArray(); boolean sawDigit = false; octets = 0; int i = 0; int cur = 0; while (i < srcb.length) { ch = srcb[i++]; if (Character.isDigit(ch)) { int sum = dst[cur] * 10 + (Character.digit(ch, 10) & 0xff); if (sum > 255) { return null; } dst[cur] = (byte) (sum & 0xff); if (!sawDigit) { if (++octets > INADDRSZ) { return null; } sawDigit = true; } } else if (ch == '.' && sawDigit) { if (octets == INADDRSZ) { return null; } cur++; dst[cur] = 0; sawDigit = false; } else { return null; } } if (octets < INADDRSZ) { return null; } return dst; } }