get Ip Byte Array From String - Java java.lang

Java examples for java.lang:byte Array to String

Description

get Ip Byte Array From String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String ip = "127.9.0.1";
        System.out.println(java.util.Arrays
                .toString(getIpByteArrayFromString(ip)));
    }//from  w  w  w.  jav  a  2  s  .  co  m

    public static byte[] getIpByteArrayFromString(String ip) {
        byte[] ret = new byte[4];
        java.util.StringTokenizer st = new java.util.StringTokenizer(ip,
                ".");
        try {
            ret[0] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
            ret[1] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
            ret[2] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
            ret[3] = (byte) (Integer.parseInt(st.nextToken()) & 0xFF);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return ret;
    }
}

Related Tutorials