C сеть: Sendto () возвращается Errno 22, EINVAL - PullRequest
0 голосов
/ 27 мая 2019

Я пытаюсь сгенерировать пакет с нуля с помощью компонентов уровня 2, 3 и 4 (а именно, Ethernet, IP и UDP).Мой сокет настроен на использование SOCK_RAW в качестве типа и IPPROTO_RAW в качестве протокола, чтобы мою программу можно было использовать для отправки других протоколов в более поздние сроки.Я строго соблюдаю справочную страницу sendto (2) (https://linux.die.net/man/2/sendto),, однако у меня все еще возникают проблемы с передачей пакета через локальный хост. Ошибка, возвращаемая моей программой, - 22, или EINVAL, указывающая, чтоЯ передал неверный аргумент.

Я уже использовал Сокеты sendto (), возвращающие EINVAL и Программирование сокетов: sendto всегда завершается ошибкой с ошибкой 22 (EINVAL) в попытке решить мою проблему. Я даже переключил сокет, чтобы использовать SOCK_DGRAM в качестве типа и IPPROTO_UDP в качестве протокола, чтобы посмотреть, было ли это как-то связано с сокетом (хотя я не верю, что это вызвало бы неверный аргументответ).

Мой код выглядит следующим образом:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <netinet/ether.h>
#include <netinet/udp.h>
#include <sys/socket.h>
#include <errno.h>

#define BUFFER 1024

int main(int argc, char *argv[]) {

        /* Socket Creation */
    int sockfd;

    if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) {
            perror("Socket");
            exit(EXIT_FAILURE);
    }

    // This will hold all of the packet's contents
    char sendbuf[BUFFER];


    /* Address Stuff */

    // Specify Address
    in_addr_t address = inet_addr("127.0.0.1");

    // Specifying Address for Sendto()
    struct sockaddr_in sendto_addr;
    memset(&sendto_addr, 0, sizeof(sendto_addr));
    sendto_addr.sin_family = AF_INET;
    sendto_addr.sin_port = htons(9623);  // Make sure the port isn't contested
    sendto_addr.sin_addr.s_addr = address;

    // Size of whole packet
    size_t total_len = 0;


    /* LAYER 2 */
    // Ethernet Header Configuration
    struct ether_header *ether = (struct ether_header *)sendbuf;
    int i;
    for (i = 0; i < 6; ++i) {
        ether -> ether_dhost[i] = 0x00; // Temporary data fill
        ether -> ether_shost[i] = 0x00; // Temporary data fill
    }
    ether -> ether_type = ETHERTYPE_IP;

    total_len += sizeof(struct ether_header);


    /* LAYER 3 */
    // IP Header Configuration
    struct ip *ip = (struct ip *)(sendbuf + sizeof(struct ether_header));

    ip -> ip_hl = 5;
    ip -> ip_v = 4;
    ip -> ip_tos = 0;
    ip -> ip_p = 17;
    ip -> ip_ttl = 255;
    ip -> ip_src.s_addr = address;
    ip -> ip_dst.s_addr = address;  

    total_len += sizeof(struct ip); 


    /* LAYER 4 */
    // UDP Header Configuration
    struct udphdr *udp = (struct udphdr *)(sendbuf + sizeof(struct ether_header) + \
                                           sizeof(struct ip));

    udp -> source = 123; // Gibberish to fill in later
    udp -> dest = 321;   // Gibberish to fill in later
    udp -> check = 0;

    total_len += sizeof(struct udphdr);


    /* Giberrish Packet Data */
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;
    sendbuf[total_len++] = 0x00;


    /* Fill in Rest of Headers */
    udp -> len = htons(total_len - sizeof(struct ether_header) - sizeof(struct ip));
    ip -> ip_len = htons(total_len - sizeof(struct ether_header));


    /* Send Packet */  // ERROR OCCURS HERE
    printf("Sockfd is %d\n", sockfd);
    printf("Total length is %d\n", total_len);
    if (sendto(sockfd, sendbuf, total_len, 0, (const struct sockaddr*)&sendto_addr, \
        sizeof(sendto_addr)) < 0) {
            printf("Error sending packet: Error %d.\n", errno);
            perror("sendto Error");
            exit(EXIT_FAILURE);
    } 

    close(sockfd);

}

Точное консольное сообщение гласит:

Sockfd равно 3
Общая длина 46
Ошибка отправки пакета: ошибка 22.
sendto Ошибка: неверный аргумент

1 Ответ

0 голосов
/ 27 мая 2019

Эврика!На самом деле это была строка:

if ((sockfd = socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW)) == -1) {
        perror("Socket");
        exit(EXIT_FAILURE);
}

Что должно было быть

if ((sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
        perror("Socket");
        exit(EXIT_FAILURE);
}

Почему это решило проблему?Отличный вопрос, хотелось бы увидеть чей-то ответ на эту тему: P

...