iphash.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 <lib9.h>
  11. #include <ip.h>
  12. /* from the kernel. Sorry. */
  13. enum {
  14. Nipht = 521, /* convenient prime */
  15. };
  16. /* Jehanne iphash() from ip/ipaux.c */
  17. uint32_t
  18. iphash(uint8_t *sa, uint16_t sp, uint8_t *da, uint16_t dp)
  19. {
  20. return (((uint32_t)(sa[IPaddrlen-1])<<24) ^ (sp << 16) ^ (((uint32_t)da[IPaddrlen-1])<<8) ^ dp ) % Nipht;
  21. }
  22. /* old Nix iphash (worked with kenc) */
  23. uint32_t oldiphash(uint8_t * sa, uint16_t sp, uint8_t * da, uint16_t dp)
  24. {
  25. return ((sa[IPaddrlen - 1] << 24) ^ (sp << 16) ^ (da[IPaddrlen - 1] << 8) ^
  26. dp) % Nipht;
  27. }
  28. /* conventions.
  29. * informational messages go on fd 2.
  30. * PASS/FAIL go on fd 1 and there is only ever one of each.
  31. * The first four characters of passing tests are PASS
  32. * The first four characters of failing tests are FAIL
  33. * It is an error to print both PASS and FAIL
  34. * FAIL tests should exits() with a message
  35. * We may consider not printing PASS/FAIL and using exits instead.
  36. */
  37. void
  38. 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%ulx, should be < 0x%ulx\n",
  49. ohash, Nipht);
  50. nhash = iphash(sa, sp, da, dp);
  51. if (nhash > Nipht)
  52. fprint(2, "iphash returns bad value: 0x%ulx, should be < 0x%ulx\n",
  53. ohash, Nipht);
  54. fprint(2, "ohash is 0x%ulx, nhash is 0x%ulx\n", ohash, nhash);
  55. if (ohash == nhash) {
  56. /* ohash and nhash should differs on gcc due to type promotion rules */
  57. fprint(2, "FAIL: iphash equals\n");
  58. exits("FAIL");
  59. }
  60. /* Always print PASS at the end. */
  61. print("PASS\n");
  62. exits("PASS");
  63. }