summaryrefslogtreecommitdiff
path: root/common/src/packet_inject.cpp
blob: 464fefaa1bd7ab9cc4708bd32c1730b59f3dd0a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#include "log.h"

int packet_inject_ipv4(struct in_addr *ip_dst, const char *data, int len)
{
    struct sockaddr_in saddr4 = {0};
    saddr4.sin_family = PF_INET;
    memcpy(&saddr4.sin_addr, ip_dst, sizeof(struct in_addr));

    int fd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);
    if (fd == -1)
    {
        LOG_ERROR("Failed at socket(PF_INET, SOCK_RAW), %d: %s", errno, strerror(errno));
        return -1;
    }

    if (sendto(fd, data, len, 0, (struct sockaddr *)&saddr4, sizeof(saddr4)) == -1)
    {
        char string[256] = {0};
        inet_ntop(PF_INET, ip_dst, string, sizeof(string));
        LOG_ERROR("Failed at send() %s, (%d: %s)", string, errno, strerror(errno));
        close(fd);
        return -1;
    }

    close(fd);
    return 0;
}

int packet_inject_ipv6(struct in6_addr *ip6_dst, const char *data, int len)
{
    struct sockaddr_in6 saddr6 = {0};
    saddr6.sin6_family = PF_INET6;
    memcpy(&saddr6.sin6_addr, ip6_dst, sizeof(struct in6_addr));

    int fd = socket(PF_INET6, SOCK_RAW, IPPROTO_RAW);
    if (fd == -1)
    {
        LOG_ERROR("Failed at socket(PF_INET6, SOCK_RAW), %d: %s", errno, strerror(errno));
        return -1;
    }

    if (sendto(fd, data, len, 0, (struct sockaddr *)&saddr6, sizeof(saddr6)) == -1)
    {
        char string[256] = {0};
        inet_ntop(PF_INET6, ip6_dst, string, sizeof(string));
        LOG_ERROR("Failed at send() %s, (%d: %s)", string, errno, strerror(errno));
        close(fd);
        return -1;
    }

    close(fd);
    return 0;
}