Fix NPE in ICMP.computeChecksum()
[controller.git] / opendaylight / sal / api / src / main / java / org / opendaylight / controller / sal / packet / ICMP.java
index 0429c0dd279e1231ace4a0bfd7c6b880163101ba..b2a1cfe8c2824b8bfab8a4b737d949e9d67df446 100644 (file)
@@ -68,7 +68,7 @@ public class ICMP extends Packet {
 
     /**
      * Sets the type for the current ICMP message
-     * 
+     *
      * @param type
      *            The ICMP message type
      * @return This ICMP object
@@ -81,7 +81,7 @@ public class ICMP extends Packet {
 
     /**
      * Sets the ICMP code (type subtype) for the current ICMP object instance
-     * 
+     *
      * @param code
      *            The ICMP message type subtype
      * @return This ICMP object
@@ -136,7 +136,7 @@ public class ICMP extends Packet {
 
     /**
      * Computes the ICMP checksum on the serialized ICMP message
-     * 
+     *
      * @param serialized
      *            The data stream
      * @param start
@@ -146,22 +146,20 @@ public class ICMP extends Packet {
      */
     short computeChecksum(byte[] data, int start) {
         int sum = 0, carry = 0, finalSum = 0;
-        int end = start + this.getHeaderSize() / NetUtils.NumBitsInAByte
-                + rawPayload.length;
-        int checksumStartByte = start + getfieldOffset(CHECKSUM)
-                / NetUtils.NumBitsInAByte;
+        int wordData;
+        int end = start + this.getHeaderSize() / NetUtils.NumBitsInAByte;
+        if (rawPayload != null) {
+            end += rawPayload.length;
+        }
+        int checksumStartByte = start + getfieldOffset(CHECKSUM) / NetUtils.NumBitsInAByte;
 
         for (int i = start; i <= (end - 1); i = i + 2) {
             // Skip, if the current bytes are checkSum bytes
             if (i == checksumStartByte) {
                 continue;
             }
-            StringBuffer sbuffer = new StringBuffer();
-            sbuffer.append(String.format("%02X", data[i]));
-            if (i < (data.length - 1)) {
-                sbuffer.append(String.format("%02X", data[i + 1]));
-            }
-            sum += Integer.valueOf(sbuffer.toString(), 16);
+            wordData = ((data[i] << 8) & 0xFF00) + (data[i + 1] & 0xFF);
+            sum = sum + wordData;
         }
         carry = (sum >> 16) & 0xFF;
         finalSum = (sum & 0xFFFF) + carry;