Wireshark не обнаруживает отправленных пакетов. отправитьвозврат 0

Я пытался отправлять пакеты с использованием сырого сокета в следующем коде. Этот код я нашел где-то в Интернете. Я создал свой собственный заголовок ipheader и udp. Весь пакет данных отправляется с помощью функции sendto () на необработанном сокете. sendto () возвращает 0. Это означает, что из него отправляется пакет нулевой длины, и, следовательно, даже wirehark не обнаруживает ни одного пакета. В чем моя ошибка?

// Must be run by root lol! Just datagram, no payload/data
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <cstdlib>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/udp.h>

// The packet length
#define PCKT_LEN 35

// Can create separate header file (.h) for all headers' structure
// The IP header's structure
struct ipheader {
    unsigned char      iph_ihl:4, iph_ver:4;
    unsigned char      iph_tos;
    unsigned short int iph_len;
    unsigned short int iph_ident;
    unsigned char      iph_flag;
    unsigned short int iph_offset;
    unsigned char      iph_ttl;
    unsigned char      iph_protocol;
    unsigned short int iph_chksum;
    unsigned int       iph_sourceip;
    unsigned int       iph_destip;
};

// UDP header's structure
struct udpheader {
    unsigned short int udph_srcport;
    unsigned short int udph_destport;
    unsigned short int udph_len;
    unsigned short int udph_chksum;
};
// total udp header length: 8 bytes (=64 bits)

// Function for checksum calculation. From the RFC,
// the checksum algorithm is:
//  "The checksum field is the 16 bit one's complement of the one's
//  complement sum of all 16 bit words in the header.  For purposes of
//  computing the checksum, the value of the checksum field is zero."
unsigned short csum(unsigned short *buf, int nwords)
{       //
    unsigned long sum;
    for(sum=0; nwords>0; nwords--)
        sum += *buf++;
    sum = (sum >> 16) + (sum &0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
}

// Source IP, source port, target IP, target port from the command line arguments
int main(int argc, char *argv[])
{
    int sd;
    // No data/payload just datagram
    char buffer[PCKT_LEN];
    // Our own headers' structures
    struct ipheader *ip = (struct ipheader *) buffer;
    struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader));
    // Source and destination addresses: IP and port
    struct sockaddr_in sin, din;
    int one = 1;
    const int *val = &one;

    memset(buffer, 0, PCKT_LEN);

    if(argc != 5)
    {
        printf("- Invalid parameters!!!\n");
        printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]);
        exit(-1);
    }

    // Create a raw socket with UDP protocol
    sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
    if(sd < 0)
    {
        perror("socket() error");
        // If something wrong just exit
        exit(-1);
    }
    else
        printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n");

    // The source is redundant, may be used later if needed
    // The address family
    sin.sin_family = AF_INET;
    din.sin_family = AF_INET;
    // Port numbers
    sin.sin_port = htons(atoi(argv[2]));
    din.sin_port = htons(atoi(argv[4]));
    // IP addresses
    sin.sin_addr.s_addr = inet_addr(argv[1]);
    din.sin_addr.s_addr = inet_addr(argv[3]);

    // Fabricate the IP header or we can use the
    // standard header structures but assign our own values.
    ip->iph_ihl = 5;
    ip->iph_ver = 4;
    ip->iph_tos = 16; // Low delay
    ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader);
    ip->iph_ident = htons(54321);
    ip->iph_ttl = 64; // hops
    ip->iph_protocol = 17; // UDP
    // Source IP address, can use spoofed address here!!!
    ip->iph_sourceip = inet_addr(argv[1]);
    // The destination IP address
    ip->iph_destip = inet_addr(argv[3]);

    // Fabricate the UDP header. Source port number, redundant
    udp->udph_srcport = htons(atoi(argv[2]));
    // Destination port number
    udp->udph_destport = htons(atoi(argv[4]));
    udp->udph_len = htons(sizeof(struct udpheader));
    // Calculate the checksum for integrity
    ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader));
    // Inform the kernel do not fill up the packet structure. we will build our own...
    if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0)
    {
        perror("setsockopt() error");
        exit(-1);
    }
    else
        printf("setsockopt() is OK.\n");

    // Send loop, send for every 2 second for 100 count
    printf("Trying...\n");
    printf("Using raw socket and UDP protocol\n");
    printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4]));

    int count;
    int i;
    for(count = 1; count <=20; count++)
    {
        if(i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)
        // Verify
        {
            perror("sendto() error");
            exit(-1);
        }
        else
        {
            printf("Count #%u - sendto() is OK. Data Length#%d\n", count,i);
            sleep(2);
        }
    }
    close(sd);
    return 0;
}

person Shashi Bhushan    schedule 24.12.2012    source источник
comment
Я отредактировал его, чтобы улучшить, но я думаю, что некоторые из исходных пространств были потеряны. Возможно, Шаши мог бы отредактировать и использовать {} для обозначения кода, а не ".   -  person Mats Petersson    schedule 24.12.2012
comment
Я думаю, однако, что 0 пакета len означает, что ничего не было отправлено, поэтому wirehark ничего не увидит, потому что вы никогда не отправляли пакет. Относительно того, почему это так, я не уверен.   -  person Mats Petersson    schedule 24.12.2012
comment
Не изобретайте велосипед, используйте libtins: D   -  person mfontanini    schedule 24.12.2012


Ответы (3)


Ага! Я получил по крайней мере часть этого.

i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0 совпадает с i = (sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)

вы, вероятно, захотите: (i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin))) < 0

Вы можете захотеть:

  1. Включите предупреждения в вашем компиляторе - по крайней мере, если вы используете gcc, это должно дать вам предупреждение для сравнения и назначения в одном и том же if-выражении.
  2. Повторите попытку с фиксированным кодом.

Я уверен, что в вашем коде могут быть и другие проблемы - я не специалист по сетям.

person Mats Petersson    schedule 24.12.2012
comment
Эй..я ... прости !! Но я все еще ничего не вижу на wirehark .. почему так? - person Shashi Bhushan; 24.12.2012
comment
Я понятия не имею. Вы уверены, что правильно настроили wirehark? Например. используя правильный интерфейс, используя правильный протокол и т. д.? - person Mats Petersson; 24.12.2012

Очень сложно прочитать этот фрагмент кода и понять, что и зачем вы делаете. Поэтому я могу рекомендовать вам взглянуть на мой фрагмент кода: реализация клиента DHCP

Посмотрите на функцию getSock (), чтобы увидеть, как создается сокет, и на функцию talker (), чтобы узнать, как формировать и отправлять завершенный пакет.

person fycth    schedule 24.12.2012
comment
почему минус? Я привел хороший пример (готовый к использованию код) того, как делать именно то, что он хочет. - person fycth; 24.12.2012
comment
Я согласен, это немного резковато - это хороший ответ. Я дал вам положительный голос! - person Mats Petersson; 24.12.2012
comment
-1 было от меня. да, вы все это сделали, но это должен был быть комментарий, так как он не касается фактического вопроса (где моя ошибка?). @ Матс Петерссон: это определенно не ответ. - person Karoly Horvath; 24.12.2012
comment
Если в коде есть ошибка, можно дать четкий ответ. С другой стороны, если код просто написан неправильно или содержит много ошибок, было бы уместнее привести хороший пример того, как решить задачу. Но ладно, забудь, у тебя есть собственный разум. - person fycth; 24.12.2012

Неправильная структура локального IP-заголовка ... я предлагаю включить IP-заголовок, поставляемый с вашим дистрибутивом (вы используете Linux? Не так ли?).

Я просто включил linux / ip.h, переименовал ссылку на структуру ipheader на iphdr и переименовал поля заголовка ip в соответствии со структурой, описанной в последнем файле.

Я пробовал обнюхивать пакеты с помощью tcpdump, и теперь он работает (я не пробовал с wirehark, но он тоже должен работать)

Попробуйте этот фиксированный код:

// Must be run by root lol! Just datagram, no payload/data
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/udp.h>
#include <linux/ip.h>

// The packet length
#define PCKT_LEN 35

// UDP header's structure
struct udpheader {
    unsigned short int udph_srcport;
    unsigned short int udph_destport;
    unsigned short int udph_len;
    unsigned short int udph_chksum;
};
// total udp header length: 8 bytes (=64 bits)

// Function for checksum calculation. From the RFC,
// the checksum algorithm is:
//  "The checksum field is the 16 bit one's complement of the one's
//  complement sum of all 16 bit words in the header.  For purposes of
//  computing the checksum, the value of the checksum field is zero."
unsigned short csum(unsigned short *buf, int nwords)
{       //
    unsigned long sum;
    for(sum=0; nwords>0; nwords--)
        sum += *buf++;
    sum = (sum >> 16) + (sum &0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
}

// Source IP, source port, target IP, target port from the command line arguments
int main(int argc, char *argv[])
{
    int sd;
    // No data/payload just datagram
    char buffer[PCKT_LEN];
    // Our own headers' structures
    struct iphdr *ip = (struct iphdr *) buffer;
    struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct iphdr));
    // Source and destination addresses: IP and port
    struct sockaddr_in sin, din;
    int one = 1;
    const int *val = &one;

    memset(buffer, 0, PCKT_LEN);

    if(argc != 5)
    {
        printf("- Invalid parameters!!!\n");
        printf("- Usage %s <source hostname/IP> <source port> <target hostname/IP> <target port>\n", argv[0]);
        exit(-1);
    }

    // Create a raw socket with UDP protocol
    sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
    if(sd < 0)
    {
        perror("socket() error");
        // If something wrong just exit
        exit(-1);
    }
    else
        printf("socket() - Using SOCK_RAW socket and UDP protocol is OK.\n");

    // The source is redundant, may be used later if needed
    // The address family
    sin.sin_family = AF_INET;
    din.sin_family = AF_INET;
    // Port numbers
    sin.sin_port = htons(atoi(argv[2]));
    din.sin_port = htons(atoi(argv[4]));
    // IP addresses
    sin.sin_addr.s_addr = inet_addr(argv[1]);
    din.sin_addr.s_addr = inet_addr(argv[3]);

    // Fabricate the IP header or we can use the
    // standard header structures but assign our own values.
    ip->ihl = 5;
    ip->version = 4;
    ip->tos = 16; // Low delay
    ip->tot_len = sizeof(struct iphdr) + sizeof(struct udpheader);
    ip->id = htons(54321);
    ip->ttl = 64; // hops
    ip->protocol = 17; // UDP
    // Source IP address, can use spoofed address here!!!
    ip->saddr = inet_addr(argv[1]);
    // The destination IP address
    ip->daddr = inet_addr(argv[3]);

    // Fabricate the UDP header. Source port number, redundant
    udp->udph_srcport = htons(atoi(argv[2]));
    // Destination port number
    udp->udph_destport = htons(atoi(argv[4]));
    udp->udph_len = htons(sizeof(struct udpheader));

    // Calculate the checksum for integrity
    ip->check = csum((unsigned short *)buffer, sizeof(struct iphdr) + sizeof(struct udpheader));

    // Inform the kernel do not fill up the packet structure. we will build our own...
    if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0)
    {
        perror("setsockopt() error");
        exit(-1);
    }
    else
        printf("setsockopt() is OK.\n");

    // Send loop, send for every 2 second for 100 count
    printf("Trying...\n");
    printf("Using raw socket and UDP protocol\n");
    printf("Using Source IP: %s port: %u, Target IP: %s port: %u.\n", argv[1], atoi(argv[2]), argv[3], atoi(argv[4]));

    int count;
    int i;
    for(count = 1; count <=20; count++)
    {
        if((i = sendto(sd, buffer, PCKT_LEN, 0, (struct sockaddr *)&sin, sizeof(sin))) < 0)
        // Verify
        {
            perror("sendto() error");
            exit(-1);
        }
        else
        {
            printf("Count #%u - sendto() is OK. Data Length# %d\n", count,i);
            sleep(2);
        }
    }
    close(sd);
    return 0;
}
person Davide Berra    schedule 24.12.2012