2 * Copyright © 2015, 2017 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.netvirt.dhcpservice.api;
11 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.math.BigInteger;
13 import java.net.InetAddress;
14 import java.net.UnknownHostException;
15 import java.util.List;
16 import javax.annotation.Nullable;
18 public abstract class DHCPUtils {
20 public static byte[] byteToByteArray(byte value) {
21 return new byte[] {value};
24 public static byte[] shortToByteArray(short value) {
25 return new byte[] {(byte) (value >> 8 & 0xff), (byte) (value & 0xff)};
28 public static byte[] intToByteArray(int value) {
29 return new byte[] {(byte) (value >> 24 & 0xff), (byte) (value >> 16 & 0xff),
30 (byte) (value >> 8 & 0xff), (byte) (value & 0xff)};
33 public static byte[] inetAddrToByteArray(InetAddress address) {
34 return address.getAddress();
37 public static byte[] strAddrToByteArray(String addr) throws UnknownHostException {
38 return InetAddress.getByName(addr).getAddress();
41 public static byte[] strListAddrsToByteArray(List<String> strList) throws UnknownHostException {
42 byte[] result = new byte[strList.size() * 4];
43 for (int i = 0; i < strList.size(); i++) {
44 byte[] addr = InetAddress.getByName(strList.get(i)).getAddress();
45 System.arraycopy(addr, 0, result, i * 4, 4);
50 public static short byteArrayToShort(@Nullable byte[] ba) {
51 if (ba == null || ba.length != 2) {
54 return (short) ((0xff & ba[0]) << 8 | 0xff & ba[1]);
58 public static InetAddress byteArrayToInetAddr(byte[] ba) {
60 return InetAddress.getByAddress(ba);
61 } catch (UnknownHostException e) {
66 // An empty byte[] would technically be an invalid MAC address and it's unclear if we can force callers to pass
68 @SuppressFBWarnings("PZLA_PREFER_ZERO_LENGTH_ARRAYS")
70 public static byte[] strMacAddrtoByteArray(String macAddress) {
71 if (macAddress == null) {
74 String[] bytes = macAddress.split(":");
75 byte[] result = new byte[bytes.length];
76 for (int i = 0; i < bytes.length; i++) {
77 BigInteger temp = new BigInteger(bytes[i], 16);
78 byte[] raw = temp.toByteArray();
79 result[i] = raw[raw.length - 1];
84 public static String byteArrayToString(byte[] bytes) {
85 StringBuilder str = new StringBuilder();
86 for (byte b : bytes) {
87 str.append(Integer.toHexString(b >>> 4 & 0x0F));
88 str.append(Integer.toHexString(b & 0x0F));
91 str.deleteCharAt(str.lastIndexOf(":"));
92 return str.toString();