使用套接字

时间:2015-12-18 13:47:44

标签: c multithreading sockets networking

我正在尝试编写一个读取网卡的程序,然后发现它是TCP还是UDP数据包。我不习惯网络协议既不使用套接字也不习惯。下面的代码是我的线程代码,它完成了读取和知道它是UDP还是TCP的工作。但是最后一个参数为0(我正在尝试接收各种数据包),我找不到合适的数据包。谢谢你们的帮助(=

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;
}

0 个答案:

没有答案