2 * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.vpnservice.dhcpservice.api;
12 import java.math.BigInteger;
13 import java.net.InetAddress;
14 import java.net.UnknownHostException;
15 import java.util.List;
17 public abstract class DHCPUtils {
19 public static byte[] byteToByteArray(byte b) {
20 return new byte[] {b};
23 public static byte[] shortToByteArray(short s) {
24 return new byte[] { (byte) ((s >> 8) & 0xff), (byte) (s & 0xff) };
27 public static byte[] intToByteArray(int i ) {
28 return new byte[] { (byte) ((i >> 24) & 0xff), (byte) ((i >> 16) & 0xff), (byte) ((i >> 8) & 0xff),
32 public static byte[] inetAddrToByteArray(InetAddress a) {
33 return a.getAddress();
36 public static byte[] strAddrToByteArray(String addr) {
38 return InetAddress.getByName(addr).getAddress();
39 } catch (UnknownHostException e) {
40 // TODO Auto-generated catch block
46 public static byte[] strListAddrsToByteArray(List<String> strList) {
47 byte[] result = new byte[strList.size() * 4];
48 byte[] addr = new byte[4];
50 for (int i = 0; i < strList.size(); i++) {
51 addr = InetAddress.getByName(strList.get(i)).getAddress();
52 System.arraycopy(addr, 0, result, i*4, 4);
54 } catch (UnknownHostException e) {
60 public static short byteArrayToShort(byte[] ba) {
61 if (ba == null || ba.length != 2) {
64 return (short) ((0xff & ba[0]) << 8 | (0xff & ba[1]));
67 public static InetAddress byteArrayToInetAddr(byte[] ba) {
69 return InetAddress.getByAddress(ba);
70 } catch (UnknownHostException e) {
75 public static byte[] strMacAddrtoByteArray(String macAddress) {
76 if(macAddress == null) {
79 String[] bytes = macAddress.split(":");
80 byte[] result = new byte[bytes.length];
81 for (int i = 0; i < bytes.length; i++) {
82 BigInteger temp = new BigInteger(bytes[i], 16);
83 byte[] raw = temp.toByteArray();
84 result[i] = raw[raw.length - 1];
89 public static String byteArrayToString(byte[] bytes) {
90 StringBuilder str = new StringBuilder();
91 for (byte b : bytes) {
92 str.append(Integer.toHexString((b >>> 4) & 0x0F));
93 str.append(Integer.toHexString(b & 0x0F));
96 str.deleteCharAt(str.lastIndexOf(":"));
97 return str.toString();