added arputil module
[vpnservice.git] / mdsalutil / mdsalutil-api / src / main / java / org / opendaylight / vpnservice / mdsalutil / NWUtil.java
1 /*
2  * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.vpnservice.mdsalutil;
9
10 import java.net.InetAddress;
11
12 import com.google.common.primitives.UnsignedBytes;
13
14 public class NWUtil {
15
16     public static  long convertInetAddressToLong(InetAddress address) {
17         byte[] ipAddressRaw = address.getAddress();
18         return (((ipAddressRaw[0] & 0xFF) << (3 * 8))
19                 + ((ipAddressRaw[1] & 0xFF) << (2 * 8))
20                 + ((ipAddressRaw[2] & 0xFF) << (1 * 8))
21                 + (ipAddressRaw[3] & 0xFF))
22                 & 0xffffffffL;
23     }
24
25     public static byte[] parseIpAddress(String ipAddress) {
26         byte cur;
27
28         String[] addressPart = ipAddress.split(".");
29         int size = addressPart.length;
30
31         byte[] part = new byte[size];
32         for (int i = 0; i < size; i++) {
33             cur = UnsignedBytes.parseUnsignedByte(addressPart[i], 16);
34             part[i] = cur;
35         }
36
37         return part;
38     }
39
40     public static byte[] parseMacAddress(String macAddress) {
41         byte cur;
42
43         String[] addressPart = macAddress.split(":");
44         int size = addressPart.length;
45
46         byte[] part = new byte[size];
47         for (int i = 0; i < size; i++) {
48             cur = UnsignedBytes.parseUnsignedByte(addressPart[i], 16);
49             part[i] = cur;
50         }
51
52         return part;
53     }
54
55     public static String toStringIpAddress(byte[] ipAddress)
56     {
57         if (ipAddress == null) {
58             return "";
59         }
60
61         StringBuilder sb = new StringBuilder(18);
62
63         for (int i = 0; i < ipAddress.length; i++) {
64             sb.append(UnsignedBytes.toString(ipAddress[i], 10));
65             sb.append(".");
66         }
67
68         sb.setLength(17);
69         return sb.toString();
70     }
71
72     public static String toStringMacAddress(byte[] macAddress)
73     {
74         if (macAddress == null) {
75             return "";
76         }
77
78         StringBuilder sb = new StringBuilder(18);
79
80         for (int i = 0; i < macAddress.length; i++) {
81             String tmp = UnsignedBytes.toString(macAddress[i], 16).toUpperCase();
82             if(tmp.length() == 1 || macAddress[i] == (byte)0) {
83                 sb.append("0");
84             }
85             sb.append(tmp);
86             sb.append(":");
87         }
88
89         sb.setLength(17);
90         return sb.toString();
91     }
92 }