-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnet.c
50 lines (43 loc) · 1.04 KB
/
net.c
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
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <net/if.h>
#include <errno.h>
#include "ethdump.h"
int
rawsocket(const char *name)
{
int s;
struct sockaddr_ll sll;
s = socket(PF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_ALL));
if (s < 0) {
fprintf(stderr, "Cannot create raw socket: %s\n", strerror(errno));
return -1;
}
memset(&sll, 0, sizeof(sll));
sll.sll_family = AF_PACKET;
sll.sll_ifindex = if_nametoindex(name);
sll.sll_protocol = htons(ETH_P_ALL);
if (bind(s, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
fprintf(stderr, "bind to %s: %s", name, strerror(errno));
close(s);
return -1;
}
return s;
}
// Read a single packet from the raw socket.
int
readpacket(int socket, struct rawpacket *p)
{
p->len = recvfrom(socket, p->buf, sizeof(p->buf), 0, NULL, NULL);
if (p->len < 0) {
fprintf(stderr, "Error receiving packet: %s\n", strerror(errno));
return -1;
}
return 0;
}