teknoraver

swap cksum

Jul 29th, 2025 (edited)
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <stdio.h>
  3. #include <asm/byteorder.h>
  4. #include <netinet/ip.h>
  5.  
  6. #define ipv4_addr(o1, o2, o3, o4) __constant_htonl( \
  7.     (o1) << 24 | \
  8.     (o2) << 16 | \
  9.     (o3) <<  8 | \
  10.     (o4))
  11.  
  12. static struct iphdr ip = {
  13.     .version = 4,
  14.     .ihl = 5,
  15.     .id = __constant_htons(0xcda3),
  16.     .frag_off = 0x40,
  17.     .ttl = 64,
  18.     .protocol = IPPROTO_UDP,
  19. };
  20.  
  21. static uint16_t ip_checksum(uint16_t *buf, size_t len)
  22. {
  23.     unsigned long sum = 0;
  24.     int i;
  25.  
  26.     for (i = 0; i < len; i++) {
  27.         sum += htons(buf[i]);
  28.         if (sum & 0x80000000)
  29.             sum = (sum & 0xFFFF) + (sum >> 16);
  30.     }
  31.  
  32.     while (sum >> 16)
  33.         sum = (sum & 0xFFFF) + (sum >> 16);
  34.  
  35.     return htons(~sum);
  36. }
  37.  
  38. static void calc_csum_print(struct iphdr *ip)
  39. {
  40.     ip->check = 0;
  41.     ip->check = ip_checksum((uint16_t *)ip, ip->ihl * 2);
  42.     printf("chk: %hx\n", ip->check);
  43. }
  44.  
  45. int main(void)
  46. {
  47.     ip.saddr = ipv4_addr(192, 168, 0, 1);
  48.     ip.daddr = ipv4_addr(10, 0, 20, 1);
  49.     calc_csum_print(&ip);
  50.  
  51.     ip.saddr = ipv4_addr(0, 1, 192, 168);
  52.     calc_csum_print(&ip);
  53.  
  54.     ip.daddr = ipv4_addr(20, 1, 10, 0);
  55.     calc_csum_print(&ip);
  56.  
  57.     ip.saddr = ipv4_addr(10, 0, 20, 1);
  58.     ip.daddr = ipv4_addr(192, 168, 0, 1);
  59.     calc_csum_print(&ip);
  60.  
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment