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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
//http://www.saminiir.com/lets-code-tcp-ip-stack-1-ethernet-arp/
//https://openvpn.net/tuntap
#ifdef PLATFORM_LINUX
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <string.h>
#include <linux/if_tun.h>
#include <linux/if.h>
#include "netdev.h"
int fd;
int tap_transmit(const void * p_data, uint16_t p_len)
{
write(fd,p_data,p_len);
return 0;
}
int main(int argc, char **argv)
{
int err;
char dev[]="tap0";
struct ifreq ifr;
if( (fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
printf("Cannot open TUN/TAP dev\n");
exit(1);
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
strncpy(ifr.ifr_name, dev,IFNAMSIZ);
if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
printf("ioctl failed for TAP\n");
close(fd);
return err;
}
struct netdev net_dev;
uint8_t mac[6];
mac[0]=0x7a;
mac[1]=0xa4;
mac[2]=0x7b;
mac[3]=0x72;
mac[4]=0x56;
mac[5]=0xa2;
memcpy(net_dev.hwaddr,mac,6); // use mac obtained from device
net_dev.ip=(192<<0)+(168<<8)+(0<<16)+(20<<24); // 192.168.0.20 // TODO: not hardcode!
net_dev.transmit=tap_transmit;
uint8_t buf[1024];
while(1)
{
uint32_t len=read(fd,buf,1024);
if(len==-1)
{
printf("read error: %s \n",strerror(errno));
}
printf("read %d bytes\n",len);
net_incoming(&net_dev,buf);
}
return 0;
}
#endif
|