Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class Main {
    public static byte[] getBodyBytes(String ip, String port, byte[] key, byte[] ips)
            throws NumberFormatException, IOException {

        String[] ipArr = ip.split("\\.");
        byte[] ipByte = new byte[4];
        ipByte[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
        ipByte[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
        ipByte[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
        ipByte[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.write(ipByte);
        if (!isNum(port))
            throw new NumberFormatException("port is not number...");
        byte[] portByte = short2bytes(Integer.parseInt(port));
        dos.write(portByte);
        //        dos.writeByte(key.getBytes().length);
        dos.write(key);
        if (ips != null && ips.length > 0 && dos != null) {
            dos.write(ips);
        }
        byte[] bs = baos.toByteArray();
        baos.close();
        dos.close();

        return bs;
    }

    public static boolean isNum(final String strNum) {
        return strNum.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
    }

    public static byte[] short2bytes(short sht) {
        byte[] sb = new byte[2];
        for (int i = 0; i < sb.length; i++) {
            sb[i] = (byte) (sht >> (i * 8) & 0xFF);
        }
        return sb;
    }

    public static byte[] short2bytes(int intvalue) {
        byte byte1 = (byte) (intvalue & 0xFF);
        byte byte2 = (byte) (intvalue >>> 8 & 0xFF);
        byte[] port = new byte[] { byte2, byte1 };
        return port;
    }
}