ICMPv6Checksum.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package de.tu_darmstadt.tk.SmartHomeNetworkSim.core.util;
  2. /**
  3. * Class for calculating checksums, taken from stackoverflow
  4. *
  5. *
  6. * @author Andreas T. Meyer-Berg
  7. */
  8. public class ICMPv6Checksum {
  9. /**
  10. * Calculate the Internet Checksum of a buffer (RFC 1071 -
  11. * http://www.faqs.org/rfcs/rfc1071.html) Algorithm is 1) apply a 16-bit 1's
  12. * complement sum over all octets (adjacent 8-bit pairs [A,B], final odd
  13. * length is [A,0]) 2) apply 1's complement to this final sum
  14. *
  15. * Notes: 1's complement is bitwise NOT of positive value. Ensure that any
  16. * carry bits are added back to avoid off-by-one errors
  17. *
  18. *
  19. * @param buf
  20. * The message
  21. * @return The checksum
  22. * @author <a href="https://stackoverflow.com/users/396747/gary-rowe">Gary Rowe</a>
  23. * @see <a href="https://stackoverflow.com/questions/4113890/how-to-calculate-the-internet-checksum-from-a-byte-in-java">https://stackoverflow.com/questions/4113890/how-to-calculate-the-internet-checksum-from-a-byte-in-java</a>
  24. */
  25. public static long calculateChecksum(byte[] buf) {
  26. int length = buf.length;
  27. int i = 0;
  28. long sum = 0;
  29. long data;
  30. // Handle all pairs
  31. while (length > 1) {
  32. // Corrected to include @Andy's edits and various comments on Stack
  33. // Overflow
  34. data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF));
  35. sum += data;
  36. // 1's complement carry bit correction in 16-bits (detecting sign
  37. // extension)
  38. if ((sum & 0xFFFF0000) > 0) {
  39. sum = sum & 0xFFFF;
  40. sum += 1;
  41. }
  42. i += 2;
  43. length -= 2;
  44. }
  45. // Handle remaining byte in odd length buffers
  46. if (length > 0) {
  47. // Corrected to include @Andy's edits and various comments on Stack
  48. // Overflow
  49. sum += (buf[i] << 8 & 0xFF00);
  50. // 1's complement carry bit correction in 16-bits (detecting sign
  51. // extension)
  52. if ((sum & 0xFFFF0000) > 0) {
  53. sum = sum & 0xFFFF;
  54. sum += 1;
  55. }
  56. }
  57. // Final 1's complement value correction to 16-bits
  58. sum = ~sum;
  59. sum = sum & 0xFFFF;
  60. return sum;
  61. }
  62. }