-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathip.c
58 lines (50 loc) · 1.4 KB
/
ip.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
51
52
53
54
55
56
57
58
#include "ip.h"
#include "icmp.h"
#include "packet.h"
#include "arpcache.h"
#include "rtable.h"
#include "arp.h"
// #include "log.h"
#include <stdio.h>
#include <stdlib.h>
#include <rtable.h>
// initialize ip header
void ip_init_hdr(struct iphdr *ip, u32 saddr, u32 daddr, u16 len, u8 proto)
{
ip->version = 4;
ip->ihl = 5; // 总长度20字节
ip->tos = 0;
ip->tot_len = htons(len);
ip->id = rand();
ip->frag_off = htons(IP_DF);
ip->ttl = DEFAULT_TTL;
ip->protocol = proto;
ip->saddr = htonl(saddr);
ip->daddr = htonl(daddr);
ip->checksum = ip_checksum(ip); // 这里校验和没有进行大小字节转换
}
// lookup in the routing table, to find the entry with the same and longest prefix.
// the input address is in host byte order
rt_entry_t *longest_prefix_match(u32 dst)
{
rt_entry_t * result = NULL;
int max_mask = 0; // 最大子网掩码
rt_entry_t * ele = NULL;
list_for_each_entry(ele, &rtable, list) {
if((ele->dest & ele->mask) == (dst & ele->mask)) { // 如果按位与有相同的
if(ele->mask >= max_mask) { // 如果本子网掩码是最大的
max_mask = ele->mask;
result = ele;
}
}
}
return result;
}
// send IP packet
//
// Different from ip_forward_packet, ip_send_packet sends packet generated by
// router itself. This function is used to send ICMP packets.
void ip_send_packet(char *packet, int len)
{
fprintf(stderr, "TODO: send ip packet.\n");
}