Merge branch 'master' into edge
[clinton/Smoothieware.git] / src / libs / Network / net_util.h
1 #ifndef _NET_UTIL_H
2 #define _NET_UTIL_H
3
4 #include <cstdint>
5 #include <cstdlib>
6 #include <cstdio>
7 #include <cstring>
8
9 #define HARDWARE_TYPE_ETHERNET 1
10
11 #define SIZEOF_MAC 6
12 #define SIZEOF_IP 4
13
14 #define MAC_STR_LEN 18
15 #define IP_STR_LEN 16
16
17 // uint16_t htons(uint16_t v);
18 #define htons(a) ((((a) >> 8) & 0xFF) | (((a) << 8) & 0xFF00))
19 #define ntohs(a) htons(a)
20
21 // uint32_t htonl(uint32_t v);
22 #define htonl(a) ((((a) >> 24) & 0x000000FF) | (((a) >> 8) & 0x0000FF00) | (((a) << 8) & 0x00FF0000) | (((a) << 24) & 0xFF000000))
23 #define ntohl(a) htonl(a)
24
25 #define compare_ip(ip1, ip2, mask) (((ip1) & (mask)) == ((ip2) & (mask)))
26
27 #define IPA(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d))
28
29 typedef uint32_t IP_ADDR;
30 typedef uint32_t* NET_PACKET;
31 typedef uint8_t* NET_PAYLOAD;
32
33 // class netcore;
34 class Encapsulated;
35 class Encapsulator;
36 class NetworkInterface;
37
38 class Encapsulated
39 {
40 public:
41 virtual int receive(NetworkInterface*, NET_PACKET, int) = 0;
42 virtual int construct(NetworkInterface*, NET_PACKET, int) = 0;
43 };
44
45 class Encapsulator : public Encapsulated
46 {
47 public:
48 virtual NET_PACKET get_new_packet_buffer(NetworkInterface*) = 0;
49 virtual NET_PAYLOAD get_payload_buffer(NET_PACKET) = 0;
50 virtual void set_payload_length(NET_PACKET, int) = 0;
51 };
52
53 class Period_receiver
54 {
55 public:
56 virtual int periodical(int, NetworkInterface*, NET_PACKET, int) = 0;
57 };
58
59 class NetworkInterface : public Encapsulator {
60 public:
61 virtual const uint8_t* get_name(void) { return interface_name; };
62 // virtual void provide_net(netcore* n){ net = n; }
63
64 // virtual bool if_up(void) = 0;
65
66 virtual bool can_read_packet(void) = 0;
67 virtual int read_packet(uint8_t**) = 0;
68 void release_read_packet(uint8_t*);
69
70 virtual bool can_write_packet(void) = 0;
71 virtual int write_packet(uint8_t *, int) = 0;
72
73 virtual void* request_packet_buffer(void) = 0;
74
75 virtual void set_ip(uint32_t new_ip) { ip_address = new_ip; };
76 virtual void set_mac(uint8_t new_mac[6]) { memcpy(mac_address, new_mac, 6); };
77
78 bool isUp() { return up; }
79
80 // netcore* net;
81 uint8_t* interface_name;
82
83 IP_ADDR ip_address;
84 IP_ADDR ip_mask;
85
86 uint8_t mac_address[6];
87
88 bool up;
89 };
90
91 extern const uint8_t broadcast[6];
92
93 bool compare_mac(const uint8_t*, const uint8_t*, const uint8_t*);
94 int format_mac(uint8_t*, uint8_t*);
95 int format_ip(uint32_t, uint8_t*);
96 int checksum16(uint8_t*, int, int);
97 uint32_t crc32(uint8_t* buf, int length);
98
99 #endif /* _NET_UTIL_H */