Skip to content

Instantly share code, notes, and snippets.

@mantoine96
Created June 11, 2015 15:15
Show Gist options
  • Save mantoine96/651f76fe08ca06ec74ee to your computer and use it in GitHub Desktop.
Save mantoine96/651f76fe08ca06ec74ee to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <stdint.h>
#include <errno.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <sys/ioctl.h>
//#include <net/if.h>
#include <netinet/ether.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <linux/netdevice.h>
#define ARP 1
/* Define structures */
typedef struct {
uint8_t mac_dest[6];
uint8_t mac_src[6];
uint16_t ether_type;
} eth_header_t;
typedef struct {
uint16_t hardware_type;
uint16_t protocol_type;
uint8_t hardware_l;
uint8_t protocol_l;
uint16_t operation;
uint8_t sender_hwa[6];
uint8_t sender_ip[4];
uint8_t target_hwa[6];
uint8_t target_ip[4];
} arp_header_t;
/* End Structures*/
eth_header_t parse_eth_header(uint8_t *buffer) { //parse eth header
int i = 0;
eth_header_t tmp;
for (i = 0; i < 6; i++) {
tmp.mac_dest[i] = buffer[i];
}
buffer += 6;
for (i = 0; i < 6; i++) {
tmp.mac_src[i] = buffer[i];
}
tmp.ether_type = (buffer[7] << 8) | buffer[6];
uint8_t *tmp_8 = (uint8_t * ) & tmp.ether_type;
tmp_8[0] = buffer[6];
tmp_8[1] = buffer[7];
return tmp;
}
/* Reading function */
int sup_read(int protocol, uint8_t *buffer, int buffer_length) {
int s;
s = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (s == -1) {
printf("Erreur lors de l'ouverture de la socket");
}
uint8_t *rx_buff = (uint8_t *) malloc(1500);
int exit = 1;
int length = 0;
while (exit) {
length = recvfrom(s, rx_buff, 65535, 0, NULL, NULL);
uint8_t *tmp1 = rx_buff;
eth_header_t tmp_head = parse_eth_header(rx_buff);
eth_header_t *eth_head = &tmp_head;
eth_head->ether_type = htons(eth_head->ether_type);
switch (eth_head->ether_type) {
case 0x0806:
if (protocol == ARP) {
tmp1 = rx_buff;
tmp1 += sizeof(eth_header_t);
length -=sizeof(eth_header_t);
memcpy(buffer,rx_buff,length);
printf("This is an ARP frame");
exit=0;
}
break;
}
}
close(s);
free(rx_buff);
return length;
}
/*End reading*/
int main(){
uint8_t *buffer = (uint8_t *) malloc(1500);
while(1){
sup_read(1, buffer, sizeof(buffer));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment