1

I'm trying to write a program that reads the network card and then discover if it is a TCP or a UDP packet. I'm not used to network protocols neither the use of sockets. The code below is the code of my thread one, it does the job of reading and knowing if it is a UDP or TCP. But with the last parameter as 0 (I'm trying to receive all sorts of packets), I'm not getting the right ones. Thanks for your help guys (=

void *Thread1(){
    int saddr_size , data_size, raw_socket, seconds, tcp, udp;
        struct sockaddr saddr;
    struct iphdr *header;
    unsigned char *buffer = (unsigned char *)malloc(65536);
    raw_socket = socket(AF_INET , SOCK_RAW , 0);
    seconds = 30;
    tcp = 0;
    udp = 0;
    while(seconds--){
        data_size = recvfrom(raw_socket , buffer , 65536 , 0 , &saddr , &saddr_size);
        header = (struct iphdr*)buffer;
        if((unsigned int)header->protocol == 6){
            printf("This is a UDP packet\n");
            //Buffer12->isTCP[seconds] = 0;
            //Buffer12->isUDP[seconds] = 1;
            //Buffer12->bytes = ntohs(udph->tot_len);           
        } else if((unsigned int)header->protocol == 17){
            printf("This is a TCP packet\n");
            //Buffer12->isTCP[seconds] = 1;
            //Buffer12->isUDP[seconds] = 0;
            //Buffer12->bytes = ntohs(tcph->tot_len);       
        }
        sleep(1);
    }

    return NULL;
}
  • General warning: [do not cast malloc return](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – LPs Dec 18 '15 at 15:07
  • Giving 0 as protocol to socket just means that you want to use the default protocol for the family/socktype pair. – LPs Dec 18 '15 at 15:37
  • You need a separate socket for each type of protocol that you want to use. You could use a `select()` statement to watch for all the sockets at the same time and then respond according to which socket has incoming data available. Suggest reading the man page for `select()` for all the details – user3629249 Dec 19 '15 at 04:29
  • What do you mean by _I'm not getting the right ones_ - do you get any packet at all with _protocol_ 0? Which OS is it? – Armali Nov 14 '17 at 06:52

0 Answers0