Эх сурвалжийг харах

added ip and udp header parsing

Douglas Andreani 5 жил өмнө
parent
commit
23a1943ce3
1 өөрчлөгдсөн 32 нэмэгдсэн , 35 устгасан
  1. 32 35
      tun/netw.c

+ 32 - 35
tun/netw.c

@@ -6,6 +6,9 @@
 #include <stdlib.h>
 #include <unistd.h>
 #include <string.h>
+#include <linux/ip.h>
+#include <linux/udp.h>
+#include <arpa/inet.h>
 
 #define MTU 1500
 
@@ -62,56 +65,50 @@ void print_packet(u_int8_t* buf, int buf_size) {
     printf("\n");
 }
 
-
-// 0100 0110 46
-// 1111 0000 
-// 0100 0000 40
-// 46 - 40 = 6
-
-// 0100 0110 46
-// 0000 1111 
-// 0000 0110 6
-// 46 - 6 = 40
-
-
-ipv4_t parse_packet(u_int8_t *buf, int buf_size) {
+void parse_packet(u_int8_t *buf, int buf_size) {
     
-    ipv4_t p;
-    p.tun_flags = buf[1]<<8 | buf[0];
-    p.tun_proto = buf[2]<<8 | buf[3];
-    p.version =  buf[4] - (buf[4] & 00001111);
-    p.header_length = buf[4] - (buf[4] & 11110000);
-    p.type_of_service = buf[5];
-    p.total_length = buf[6]<<8 | buf[7];
-    p.identification = buf[8]<<8 | buf[9];
-    p.flags = buf[10] - (buf[10] & 00011111);
-    return p;
+  
+    //struct ethhdr * ethernet_header;
+    struct iphdr * ip_header;
+    struct udphdr * udp_header;
+    ip_header = (struct iphdr*)(buf);
+    
+    if (ip_header->protocol == IPPROTO_UDP)
+    {
+        printf("UDP packet found\n");
+        printf("TTL: %d \n",ip_header->ttl);
+        printf("Dest IP address: %s\n", inet_ntoa( *(struct in_addr*)&ip_header->daddr));
+        printf("Source IP address: %s\n", inet_ntoa( *(struct in_addr*)&ip_header->saddr));
+
+        udp_header =    (struct udphdr *) (buf + ip_header->ihl*4);
+        printf("Source Port: %d\n", ntohs(udp_header->source));
+        printf("Dest Port: %d\n", ntohs(udp_header->dest));
+        if (ntohs(udp_header->dest) == 53) 
+        {
+            printf("Found DNS packet\n");
+        }
+    }
+
+    return;// NULL;
 }
 
 int main (int argc, char** argv) {
     char tun_name[IFNAMSIZ];
     u_int8_t buf[MTU];
     int ret;
-    ipv4_t curr_packet;
+    //ipv4_t curr_packet;
 
     sprintf(tun_name, "tun01");
-    int tunfd = create_tun(tun_name, (IFF_TUN));
+    int tunfd = create_tun(tun_name, (IFF_TUN | IFF_NO_PI));
     if (tunfd < 0) {
         fprintf(stderr, "could not allocate device tun.\n");
         return(EXIT_FAILURE);
     }
-    
+
     for (;;) {
         ret = read(tunfd, buf, MTU);
-        curr_packet = parse_packet(buf, ret);
-
-        if (curr_packet.tun_proto == 0x800) {
-            printf("proto: %02X\n", curr_packet.tun_proto);
-            printf("version: %02X\n", curr_packet.version);
-            printf("header length %02X\n", curr_packet.header_length);
-            print_packet(buf, ret);
-        }
+        parse_packet(buf, ret);
     }
    
     return (0);
-}
+}