Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * $Id$
 *
 * Copyright (C) 2006 Mark Bednarczyk, Sly Technologies, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc.,
 * 59 Temple Place,
 * Suite 330, Boston,
 * MA 02111-1307 USA
 * 
 */

import java.util.StringTokenizer;

public class Main {
    /**
     * Return current IP address as byte array, for V4 that will be 4 bytes for
     * V6 16.
     * 
     * @param address
     *            String representation of IP address. Both V4 and V6 type
     *            addresses are accepted.
     * @return IP Byte array representation of the address. Check Array.length
     *         to get the size of the array.
     */
    public static byte[] parseByteArray(String address) throws IllegalArgumentException {

        StringTokenizer st;
        byte[] v;

        if (address.indexOf('.') != -1) {
            st = new StringTokenizer(address, ".");
            v = new byte[4];
        } else if (address.indexOf(':') != -1) {
            st = new StringTokenizer(address, ":");
            v = new byte[16];
        } else {
            throw new IllegalArgumentException(
                    "Illegal IP address format. Expected a string in either '.' or ':' notation");
        }

        for (int i = 0; i < v.length; i++) {
            String t = st.nextToken();

            if (t == null && i != v.length) {
                throw new IllegalArgumentException("Illegal IP address format. String has too few byte elements.");
            }

            v[i] = (byte) Integer.parseInt(t);
        }

        return (v);
    }
}