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;
17 public abstract class DHCPUtils {
19 public static byte[] byteToByteArray(byte value) {
20 return new byte[] {value};
23 public static byte[] shortToByteArray(short value) {
24 return new byte[] {(byte) (value >> 8 & 0xff), (byte) (value & 0xff)};
27 public static byte[] intToByteArray(int value) {
28 return new byte[] {(byte) (value >> 24 & 0xff), (byte) (value >> 16 & 0xff),
29 (byte) (value >> 8 & 0xff), (byte) (value & 0xff)};
32 public static byte[] inetAddrToByteArray(InetAddress address) {
33 return address.getAddress();
36 public static byte[] strAddrToByteArray(String addr) throws UnknownHostException {
37 return InetAddress.getByName(addr).getAddress();
40 public static byte[] strListAddrsToByteArray(List<String> strList) throws UnknownHostException {
41 byte[] result = new byte[strList.size() * 4];
42 for (int i = 0; i < strList.size(); i++) {
43 byte[] addr = InetAddress.getByName(strList.get(i)).getAddress();
44 System.arraycopy(addr, 0, result, i * 4, 4);
49 public static short byteArrayToShort(byte[] ba) {
50 if (ba == null || ba.length != 2) {
53 return (short) ((0xff & ba[0]) << 8 | 0xff & ba[1]);
56 public static InetAddress byteArrayToInetAddr(byte[] ba) {
58 return InetAddress.getByAddress(ba);
59 } catch (UnknownHostException e) {
64 // An empty byte[] would technically be an invalid MAC address and it's unclear if we can force callers to pass
66 @SuppressFBWarnings("PZLA_PREFER_ZERO_LENGTH_ARRAYS")
67 public static byte[] strMacAddrtoByteArray(String macAddress) {
68 if (macAddress == null) {
71 String[] bytes = macAddress.split(":");
72 byte[] result = new byte[bytes.length];
73 for (int i = 0; i < bytes.length; i++) {
74 BigInteger temp = new BigInteger(bytes[i], 16);
75 byte[] raw = temp.toByteArray();
76 result[i] = raw[raw.length - 1];
81 public static String byteArrayToString(byte[] bytes) {
82 StringBuilder str = new StringBuilder();
83 for (byte b : bytes) {
84 str.append(Integer.toHexString(b >>> 4 & 0x0F));
85 str.append(Integer.toHexString(b & 0x0F));
88 str.deleteCharAt(str.lastIndexOf(":"));
89 return str.toString();