about summary refs log tree commit diff stats
path: root/src/transmit.c
blob: 2c0fbc8a32009f6288369914f008942f5f8275e1 (plain) (blame)
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
#include "transmit.h"

#include <libwifi.h>
#include <linux/if_packet.h>
#include <netinet/ether.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

static pthread_mutex_t socket_mutex = PTHREAD_MUTEX_INITIALIZER;

int send_packet(int sock, int device_index, const unsigned char dst_addr[6], const unsigned char *packet, int packet_size)
{
  struct sockaddr_ll socket_address = {0};
  socket_address.sll_family = AF_PACKET;
  socket_address.sll_ifindex = device_index;
  socket_address.sll_halen = ETH_ALEN;
  memcpy(socket_address.sll_addr, dst_addr, 6);

  pthread_mutex_lock(&socket_mutex);

  int ret = 0;
  if (sendto(sock, packet, packet_size, 0, (struct sockaddr *)&socket_address, sizeof(struct sockaddr_ll)) < 0)
  {
    printf("Could not send packet: %d\n", errno);
    ret = errno;
  }

  pthread_mutex_unlock(&socket_mutex);

  return ret;
}

int send_packet_with_radiotap(int sock, int device_index, const unsigned char dst_addr[6], const unsigned char* packet, int packet_size)
{
  struct libwifi_radiotap_info radiotap_info = {0};
  radiotap_info.present = (1 << IEEE80211_RADIOTAP_FLAGS) | (1 << IEEE80211_RADIOTAP_RATE);
  radiotap_info.flags = IEEE80211_RADIOTAP_F_FCS | IEEE80211_RADIOTAP_F_SHORTPRE;
  radiotap_info.rate_raw = 4;

  unsigned char radiotap_buffer[256];
  int radiotap_size = libwifi_create_radiotap(&radiotap_info, radiotap_buffer);
  
  uint32_t fcs = libwifi_calculate_fcs(packet, packet_size);

  int buffer_size = radiotap_size + packet_size + sizeof(uint32_t);
  unsigned char* buffer = (unsigned char*)malloc(buffer_size);

  memcpy(buffer, radiotap_buffer, radiotap_size);
  memcpy(buffer + radiotap_size, packet, packet_size);
  memcpy(buffer + radiotap_size + packet_size, (unsigned char*)&fcs, sizeof(uint32_t));

  int ret = send_packet(sock, device_index, dst_addr, buffer, buffer_size);

  return ret;
}