iphash.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <ip.h>
  12. /* from the kernel. Sorry. */
  13. enum {
  14. Nipht = 521, /* convenient prime */
  15. };
  16. uint32_t newiphash(uint8_t * sa, uint16_t sp, uint8_t * da, uint16_t dp)
  17. {
  18. uint32_t kludge;
  19. kludge =
  20. ((sa[IPaddrlen - 1] << 24) ^ (sp << 16) ^ (da[IPaddrlen - 1] << 8) ^
  21. dp);
  22. return kludge % Nipht;
  23. }
  24. uint32_t oldiphash(uint8_t * sa, uint16_t sp, uint8_t * da, uint16_t dp)
  25. {
  26. return ((sa[IPaddrlen - 1] << 24) ^ (sp << 16) ^ (da[IPaddrlen - 1] << 8) ^
  27. dp) % Nipht;
  28. }
  29. /* conventions.
  30. * informational messages go on fd 2.
  31. * PASS/FAIL go on fd 1 and there is only ever one of each.
  32. * The first four characters of passing tests are PASS
  33. * The first four characters of failing tests are FAIL
  34. * It is an error to print both PASS and FAIL
  35. * FAIL tests should exits() with a message
  36. * We may consider not printing PASS/FAIL and using exits instead.
  37. */
  38. int main()
  39. {
  40. static uint8_t sa[IPaddrlen] = { 0x80, };
  41. static uint8_t da[IPaddrlen];
  42. uint16_t sp = 4;
  43. uint16_t dp = 5;
  44. uint32_t ohash, nhash;
  45. sa[IPaddrlen - 1] = 0x80;
  46. ohash = oldiphash(sa, sp, da, dp);
  47. if (ohash > Nipht)
  48. fprint(2, "oldiphash returns bad value: 0x%lx, should be < 0x%lx\n",
  49. ohash, Nipht);
  50. nhash = newiphash(sa, sp, da, dp);
  51. if (nhash > Nipht)
  52. fprint(2, "newiphash returns bad value: 0x%lx, should be < 0x%lx\n",
  53. ohash, Nipht);
  54. fprint(2, "ohash is 0x%lx, nhash is 0x%lx\n", ohash, nhash);
  55. if (ohash == nhash) {
  56. exits("FAIL:iphash failed. ohash and nhash should differ\n");
  57. }
  58. /* Always print PASS at the end. */
  59. print("PASS\n");
  60. return 0;
  61. }