Reading MLDv2 queries using an IPv6 socket - sockets

I have mrd6 installed on my raspberry pi. It registers with a local interface (tun0) and periodically transmits MLDv2 queries over it.
According to [RFC3810], MLDv2 message types are a subset of ICMPv6 messages, and are identified in IPv6 packets by a preceding Next Header value of 58 (0x3a). They are sent with a link-local IPv6 Source Address, an IPv6 Hop Limit of 1, and an IPv6 Router Alert option [RFC2711] in a Hop-by-Hop Options header.
I can confirm that I'm seeing these packets periodically over tun0:
pi#machine:~ $ sudo tcpdump -i tun0 ip6 -vv -XX
01:22:52.125915 IP6 (flowlabel 0x71df6, hlim 1, next-header Options (0)
payload length: 36)
fe80::69bf:be2d:e087:9921 > ip6-allnodes: HBH (rtalert: 0x0000) (padn)
[icmp6 sum ok] ICMP6, multicast listener query v2 [max resp delay=10000]
[gaddr :: robustness=2 qqi=125]
0x0000: 6007 1df6 0024 0001 fe80 0000 0000 0000 `....$..........
0x0010: 69bf be2d e087 9921 ff02 0000 0000 0000 i..-...!........
0x0020: 0000 0000 0000 0001 3a00 0502 0000 0100 ........:.......
0x0030: 8200 b500 2710 0000 0000 0000 0000 0000 ....'...........
0x0040: 0000 0000 0000 0000 027d 0000 .........}..
I have a socket set up in my application on tun0 as follows, since I expect these to be ICMP packets:
int fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6); // ICMP
// ... bind this socket to tun0
int interfaceIndex = // tun0 interface Index
int mcastTTL = 10;
int loopBack = 1;
if (setsockopt(listener->socket,
IPPROTO_IPV6,
IPV6_MULTICAST_IF,
&interfaceIndex,
sizeof(interfaceIndex))
< 0) {
perror("setsockopt:: IPV6_MULTICAST_IF:: ");
}
if (setsockopt(listener->socket,
IPPROTO_IPV6,
IPV6_MULTICAST_LOOP,
&loopBack,
sizeof(loopBack))
< 0) {
perror("setsockopt:: IPV6_MULTICAST_LOOP:: ");
}
if (setsockopt(listener->socket,
IPPROTO_IPV6,
IPV6_MULTICAST_HOPS,
&mcastTTL,
sizeof(mcastTTL))
< 0) {
perror("setsockopt:: IPV6_MULTICAST_HOPS:: ");
}
struct ipv6_mreq mreq6 = {{{{0}}}};
MEMCOPY(&mreq6.ipv6mr_multiaddr.s6_addr, sourceAddress, 16);
mreq6.ipv6mr_interface = interfaceIndex;
if (setsockopt(listener->socket,
IPPROTO_IPV6,
IPV6_JOIN_GROUP,
&mreq6,
sizeof(mreq6))
< 0) {
perror("setsockopt:: IPV6_JOIN_GROUP:: ");
}
Setting up the socket this way, I can receive ICMP echo requests, replies to my own address, and multicasts sent using the link-local multicast address. However, I don't see any MLDv2 queries.
Here's my receive loop:
uint8_t received[1000] = { 0 };
struct sockaddr_storage peerAddress = { 0 };
socklen_t addressLength = sizeof(peerAddress);
socklen_t addressLength = sizeof(peerAddress);
int receivedLength = recvfrom(sockfd,
received,
sizeof(received),
0,
(struct sockaddr *)&peerAddress,
&addressLength);
if (receivedLength > 0) {
// Never get here for MLDv2 queries.
}
Researching this a bit further, I discovered the IPV6_ROUTER_ALERT socket option, which the man page describes as follows:
IPV6_ROUTER_ALERT
Pass forwarded packets containing a router alert hop-by-hop option to this socket.
Only allowed for SOCK_RAW sockets. The tapped packets are not forwarded by the
kernel, it is the user's responsibility to send them out again. Argument is a
pointer to an integer. A positive integer indicates a router alert option value
to intercept. Packets carrying a router alert option with a value field
containing this integer will be delivered to the socket. A negative integer
disables delivery of packets with router alert options to this socket.
So I figured I was missing this option, and tried setting it as follows. [RFC2710] 0 means Multicast Listener Discovery message.
int routerAlertOption = 0;
if (setsockopt(listener->socket,
IPPROTO_IPV6,
IPV6_ROUTER_ALERT,
&routerAlertOption,
sizeof(routerAlertOption))
< 0) {
perror("setsockopt:: IPV6_ROUTER_ALERT:: ");
}
However, this gives me the ENOPROTOOPT error (errno 92). Some more Googling (http://www.atm.tut.fi/list-archive/usagi-users-2005/msg00317.html) led me to the fact that you can't set the IPV6_ROUTER_ALERT option with the IPPROTO_ICMPV6 protocol. It needs a socket defined using the IPPROTO_RAW protocol.
However, defining my socket as:
int fd = socket(AF_INET6, SOCK_RAW, IPPROTO_RAW);
means I'm not able to receive any ICMP packets in my recvfrom anymore.
TL;DR: How do I read MLDv2 queries using an IPv6 socket?
edit (answer):
It appears conventional implementations of Linux will drop MLDv2 packets when passing them to an ICMPV6 socket. Why this is, I'm not sure. (Could be because of the next-header option.)
I followed the accepted answer below and went with an approach of reading raw packets on the tun0 interface. I followed the ping6_ll.c example here: http://www.pdbuchan.com/rawsock/rawsock.html.
It uses a socket with (SOCK_RAW, ETH_P_ALL). You can also set some SOL_PACKET options to filter on specific multicast rules on your interface.

From a quick look at RFCs things aren't looking good. Per RFC4443 (ICMPv6) 2.4:
2.4. Message Processing Rules
Implementations MUST observe the following rules when processing
ICMPv6 messages (from [RFC-1122]):
(b) If an ICMPv6 informational message of unknown type is received,
it MUST be silently discarded.
According to MLDv2 spec it makes use of types 130, 143, perhaps something else (not seeing more diagrams in the RFC), while valid ICMPv6 types are 1, 2, 3, 4, 101, 107, 127, 128, 129, 200, 201, 255.
It looks like the implementation (kernel) must drop MLDv2 packets if they are to be passed to an ICMPv6 socket. Personally I don't see much sense in making MLDv2 look like ICMPv6 if conventional implementations will drop the packet anyways, but I didn't see anything that contradicts this claim.
You can surely go deeper and use a raw socket, especially given that your stack doesn't recognize MLDv2 (perhaps there's a kernel patch to fix that?). But you'll have to parse IP and ICMP headers on your own then.

Related

Can I set an arbitrary value for a IP packet's total length?

When I use raw socket to forge a IP packet, it seems that I can set an arbitrary value for its total length without regarding the true size of IP packet.
However, when I use Wireshark to catch the packet, I found the total length has been corrected to be the true size. This really confused me.
Can somebody explain this issue? I will be very grateful for your help.
Thanks.
When sending a packet larger than its actual size, the additional data in the payload is a chunk of zeroes. That's what in theory you should see on a captured packet of this kind when inspecting it with Wireshark (or tcpdump). For instance:
IP 192.168.0.3.17664 > 178.60.128.48.1: tcp 32
0x0000: 4500 0064 f0d0 4000 4006 56ab c0a8 0003 E..d..#.#.V.....
0x0010: b23c 8030 4500 0001 0000 0000 ff06 dbe4 .<.0E...........
0x0020: c0a8 0003 b23c 8030 04d2 0050 0000 0000 .....<.0...P....
0x0030: 0000 0000 5002 16d0 b3c4 0000 4142 4344 ....P.......ABCD
0x0040: 4546 4748 494a 4b4c 4d4e 4f50 5152 5354 EFGHIJKLMNOPQRST
0x0050: 5556 5758 595a 0000 0000 0000 0000 0000 UVWXYZ..........
0x0060: 0000 0000 ....
This is TCP packet to google.com (178.60.128.48). The payload is "ABC...XYZ", but the IP's total_length has been manually increased. The result is zero padding in the payload until completing the total length of the packet.
That said, my bet is that the problem is in the sendto system call. This is the call that actually sends a packet on the socket. But this call also sets the total_length of the packet.
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
I suspect you have tweaked the packet's total_length field in the IPv4 header, but the len parameter on the sendto call has not been modified, so the packet's total length is overwritten to its original size when is sent.
That's my suspicion but it's hard to tell without checking the code.

Are there a constants in scapy for TCP and UDP?

Are there a constants in scapy for TCP and UDP?
I mean
TCP=6, UDP=17
etc...
a)
looking up the implementation for IP we see that IP.proto is a ByteEnumField("proto", 0, IP_PROTOS),. This means, it takes values from the IP_PROTOS list which just loads your os /etc/protocols/. So you could either parse /etc/protocols yourself or, of scapy is already loaded, access the IP_PROTOS object directly:
>>> IP_PROTOS
</etc/protocols/ pim ip ax_25 esp tcp ah mpls_in_ip rohc ipv6_opts xtp st mobility_header dccp igmp ipv6_route igp ddp etherip wesp xns_idp ipv6_frag vrrp gre ipcomp encap ipv6 iso_tp4 sctp ipencap rsvp hip udp ggp hmp idpr_cmtp hopopt fc skip icmp pup manet isis rdp l2tp ipv6_icmp udplite egp ipip ipv6_nonxt eigrp idrp shim6 rspf ospf vmtp>
>>> IP_PROTOS.tcp
6
>>> IP_PROTOS.udp
17
>>> IP_PROTOS.ip
0
b) An alternative approach would be to read scapys layer binding information directly. This is the information that is added to a layer when you (or scapy core itself) calls bind_layers(lower,upper[,overload_fields]). You can easily read that information as follows:
>>> TCP.overload_fields
{<class 'scapy.layers.inet6.IPv6'>: {'nh': 6}, <class 'scapy.layers.inet.IP'>: {'frag': 0, 'proto': 6}}
Means, in case TCP is a payload to IPv4 (scapy.layers.inet.IP) it will override IP.proto=6.
Here's that same information for UDP
>>> UDP.overload_fields
{<class 'scapy.layers.inet6.IPv6'>: {'nh': 17}, <class 'scapy.layers.inet.IP'>: {'frag': 0, 'proto': 17}}
For reference, here is the bind_layers call for TCP/UDP
TCP and UDP are the initiators of TCP/UDP packets.
For example:
pack = IP(dst="www.google.com") / UDP(dport=80)
pack.show()
Result:
>>> pack = IP(dst="www.google.com") / UDP(dport=80)
>>> pack.show()
###[ IP ]###
version= 4
ihl= None
tos= 0x0
len= None
id= 1
flags=
frag= 0
ttl= 64
proto= udp
chksum= None
src= 'Your local address'
dst= Net('www.google.com')
\options\
###[ UDP ]###
sport= domain
dport= http
len= None
chksum= None
>>>

packetsocket opened on loopback device receives all the packets twice. How to filter these duplicate entries?

when i open a packetsocket on a loopback interface (lo) and listen all the packets are seen twice. why is it so?
But a capture on the interface using tcpdump correctly ignores the duplicate entries. see the 'packets received by filter' (which contains the duplicate packets) and 'packets captured'. How is this filtering done
tcpdump -i lo -s 0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo, link-type EN10MB (Ethernet), capture size 65535 bytes
11:00:08.439542 IP 12.0.0.3 > localhost.localdomain: icmp 64: echo request seq 1
11:00:08.439559 IP localhost.localdomain > 12.0.0.3: icmp 64: echo reply seq 1
11:00:09.439866 IP 12.0.0.3 > localhost.localdomain: icmp 64: echo request seq 2
11:00:09.439884 IP localhost.localdomain > 12.0.0.3: icmp 64: echo reply seq 2
11:00:10.439389 IP 12.0.0.3 > localhost.localdomain: icmp 64: echo request seq 3
11:00:10.439410 IP localhost.localdomain > 12.0.0.3: icmp 64: echo reply seq 3
6 packets captured
12 packets received by filter
0 packets dropped by kernel
My code:
int main()
{
int sockFd;
if ( (sockFd=socket(PF_PACKET, SOCK_DGRAM, 0))<0 ) {
perror("socket()");
return -1;
}
/* bind the packet socket */
struct sockaddr_ll addr;
struct ifreq ifr;
strncpy (ifr.ifr_name, "lo", sizeof(ifr.ifr_name));
if(ioctl(sockFd, SIOCGIFINDEX, &ifr) == -1)
{
perror("iotcl");
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sll_family=AF_PACKET;
addr.sll_protocol=htons(ETH_P_ALL);
addr.sll_ifindex=ifr.ifr_ifindex;
if ( bind(sockFd, (struct sockaddr *)&addr, sizeof(addr)) ) {
perror("bind()");
return -1;
}
char buffer[MAX_BUFFER+1];
int tmpVal = 1;
while(tmpVal > 0)
{
tmpVal = recv (sockFd, buffer, MAX_BUFFER, 0);
cout<<"Received Pkt with Bytes "<<tmpVal <<endl;
}
}
Figured out the problem.
from libcaps code:
* - The loopback device gives every packet twice; on 2.2[.x] kernels,
* if we use PF_PACKET, we can filter out the transmitted version
* of the packet by using data in the "sockaddr_ll" returned by
* "recvfrom()", but, on 2.0[.x] kernels, we have to use
* PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
* "sockaddr_pkt" which doesn't give us enough information to let
* us do that.
the listening entity needs to filter the duplicate packet using the if_index got from recvfrom api.

Car OBDII WLAN protocol

I am currently searching for the specification of the WLAN protocoll to get OBDII data. There are some ELM327 similar adapter on the market which enables iPhone to connect to a OBDII interface with WLAN. This because Bluetooth serial port is scrambled because of the accessories interface. Other programs like Torque for android can also use this communication protocol. However I did not find the specs for creating a network client.
Any help is welcomed,
Thanks
Ok, after some more research, I found two sources:
Michael Gile has an open source library for iOS devices, meant for communicating with OBDII WiFi as well as Bluetooth devices.
PLX devices (creators of the KiWi) have a description how to communicate with the KiWi. The description is too large to include here, but it boils down to:
Connect using WiFi (sockets)
Wait until the device returns >
Issue command and await response
Requesting information can be done by sending a command in this format (ASCII characters):
MM PP\r
where MM is the test mode, PP is the PID, and \r is a carriage return (hex: 0x0d). All whitespace characters are ignored by the Kiwi. *Test modes 03 and 04 do not require a PID value.
The 'test modes' that are spoken of, are the ten diagnostic modes as defined in the SAE J1979 standard:
Test mode Description
01 Show current data
02 Show freeze frame data
03 Show diagnostic trouble codes
04 Clear trouble codes and stored values
05 Test results, oxygen sensors
06 Test results, non-continuously monitored
07 Show 'pending' trouble codes
08 Special control mode
09 Request vehicle information
0A Request permanent trouble codes
The PID values are the codes for the sensors in the car. A (non-exhaustive)list of possible PID values is on Wikipedia.
here what i do in C and socket:
int sockfd = 0, n = 0;
char recvBuff[1024];
struct sockaddr_in serv_addr;
char *ip = "192.168.0.10";
char str [128];
int i;
memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(35000);
if(inet_pton(AF_INET, ip, &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
printf ("reading...\n");
strcpy (str,"AT Z\x0d");
sleep(2);
write (sockfd, str, strlen (str));
while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
{
recvBuff[n] = 0;
printf ("received: ");
if(fputs(recvBuff, stdout) == EOF)
{
printf("\n Error : Fputs error\n");
}
printf ("\r\ntype: ");
fgets (str, sizeof (str), stdin);
i = strlen (str);
if (str [i-1] == 0x0a)
str [i-1] = 0;
strcat (str, "\x0d");
write (sockfd, str, strlen (str));
printf ("\r\n");
}
type 1 or 2 enter, you should see the prompt: ELM327
then after that, type whatever you want, for ex.: AT RV (will show voltage)
then use this pdf for all code:
https://www.obd-2.de/carcode/dl/ELM327DS.pdf
Have a look at ELM327 datasheet
Wifi dongles transparently bind the ELM327 RS232 port to a TCP server.
There's not really a WIFI protocol. You can use the ELM327 protocol via a raw TCP connection instead.
You can sent AT commands and OBD2 commands known as PID's with the telnet command:
telnet 192.168.0.1 35000
On succesful connection you can try to send:
AT Z
and the server should respond with "ELM327" and a version number.

having trouble returning a best possible interface from a set of routing entries

so i am trying to return a best possible matching interface from routing entries. However, it is not exactly working the way i want it to. I got 5 out 6 values returned the way should be but I am pretty sure I have a million entries in a routing table my algorithm would not work.
I am using Binary Search to solve this problem. But, for example, the interface that i want to return has a ipaddress which is smaller than the ipaddress i am passing as an argument, then the binary search algorithm does not work. the structure looks like this:
struct routeEntry_t
{
uint32_t ipAddr;
uint32_t netMask;
int interface;
};
routeEntry_t routing_table[100000];
let's say the routing table looks like this:
{ 0x00000000, 0x00000000, 1 }, // [0]
{ 0x0A000000, 0xFF000000, 2 }, // [1]
{ 0x0A010000, 0xFFFF0000, 10 }, // [2]
{ 0x0D010100, 0xFFFFFF00, 4 }, // [3]
{ 0x0B100000, 0xFFFF0000, 3 }, // [4]
{ 0x0A010101, 0xFFFFFFFF, 5 }, // [5]
Example input/output:
Regular search
Input: 0x0D010101 Output: 4 (entry [3])
Input: 0x0B100505 Output: 3 (entry [4])
To find an arbitrary address, it should go to the default interface.
Input: 0x0F0F0F0F Output: 1 (entry [0])
To find an address that matches multiple entries, take the best-match.
Input: 0x0A010200 Output: 10 (entry [2])
Input: 0x0A050001 Output: 2 (entry [1])
Input: 0x0A010101 Output: 5 (entry [5])
But my output looks like 2, 3, 1, 10, 1, 5. I don't understand where I am messing things up. Could you please explain where I am doing wrong? any help would be great. Thanks in advance. However this is what my algorithm looks like (assuming the entries are sorted):
int interface(uint32_t ipAddr)
{
int start = 0;
int end = SIZE-1;
int mid = 0;
vector<int> matched_entries;
vector<int>::iterator it;
matched_entries.reserve(SIZE);
it = matched_entries.begin();
if (start > end)
return -1;
while (start <= end)
{
mid = start + ((end-start)/2);
if (routing_table[mid].ipAddr == ipAddr)
return routing_table[mid].interface;
else if (routing_table[mid].ipAddr > ipAddr)
{
uint32_t result = routing_table[mid].netMask & ipAddr;
if (result == routing_table[mid].ipAddr)
{
matched_entries.push_back(mid);
}
end = mid-1;
}
else
{
uint32_t result = routing_table[mid].netMask & ipAddr;
if (result == routing_table[mid].ipAddr)
{
matched_entries.insert(it,mid);
}
start = mid+1;
}
}
int matched_ip = matched_entries.back();
if (routing_table[matched_ip].netMask & ipAddr)
return routing_table[matched_ip].interface;
else
return routing_table[0].interface;
}
The "right" interface is the entry with the most specific netmask whose IP address is on the same subnet as your input.
Let's look at what netmasks are, and how they work, in more detail.
Notation
Although netmasks are usually written in dotted-decimal or hex notation, the binary representation of an IPv4 netmask is always 32 bits; that is, it's exactly the same length as an IP address. The netmask always starts with zero or more 1 bits and is padded with 0 bits to complete its 32-bit length. When a netmask is applied to an IP address, they're "lined up" bit by bit. The bits in the IP address that correspond to the 1 bits in the netmask determine the network number of the IP address; those corresponding to the 0 bits in the netmask determine the device number.
Purpose
Netmasks are used to divide an address space into smaller subnets. Devices on the same subnet can communicate with each other directly using the TCP/IP protocol stack. Devices on different subnets must use one or more routers to forward data between them. Because they isolate subnets from each other, netmasks are a natural way to create logical groupings of devices. For example, each location or department within a company may have its own subnet, or each type of device (printers, PCs, etc.) may have its own subnet.
Example netmasks:
255.255.255.128 → FF FF FF 10 → 1111 1111 1111 1111 1111 1111 1000 0000
This netmask specifies that the first 25 bits of an IP address determine the network number; the final 7 bits determine the device number. This means there can be 225 different subnets, each with 27 = 128 devices.*
255.255.255.0 → FF FF FF 00 → 1111 1111 1111 1111 1111 1111 0000 0000
This netmask specifies an address space with 224 subnets, each with 28 = 256 individual addresses. This is a very common configuration—so common that it's known simply as a "Class C" network.
255.255.192.0 → FF FF FC 00 → 1111 1111 1111 1111 1111 1100 0000 0000
This netmask specifies 222 subnets, each with 210 = 1024 addresses. It might be used inside a large corporation, where each department has several hundred devices that should be logically grouped together.
An invalid netmask (note the internal zeroes):
255.128.255.0 → FF 80 FF 00 → 1111 1111 1000 0000 1111 1111 0000 0000
Calculations
Here are a few examples that show how a netmask determines the network number and the device number of an IP address.
IP Address: 192.168.0.1 → C0 A8 00 01
Netmask: 255.255.255.0 → FF FF FF 00
This device is on the subnet 192.168.0.0. It can communicate directly with other devices whose IP addresses are of the form 192.168.0.x
IP Address: 192.168.0.1 → C0 A8 00 01
IP Address: 192.168.0.130 → C0 A8 00 82
Netmask: 255.255.255.128 → FF FF FF 80
These two devices are on different subnets and cannot communicate with each other without a router.
IP Address: 10.10.195.27 → 0A 0A C3 1B
Netmask: 255.255.0.0 → FF FF 00 00
This is an address on a "Class B" network that can communicate with the 216 addresses on the 10.10.0.0 network.
You can see that the more 1 bits at the beginning of a netmask, the more specific it is. That is, more 1 bits create a "smaller" subnet that consists of fewer devices.
Putting it all together
A routing table, like yours, contains triplets of netmasks, IP addresses, and interfaces. (It may also contain a "cost' metric, which indicates which of several interfaces is the "cheapest" to use, if they are both capable of routing data to a particular destination. For example, one may use an expensive dedicated line.)
In order to route a packet, the router finds the interface with the most specific match for the packet's destination. An entry with an address addr and a netmask mask matches a destination IP address dest if (addr & netmask) == (dest & netmask), where & indicates a bitwise AND operation. In English, we want the smallest subnet that is common to both addresses.
Why? Suppose you and a colleague are in a hotel that's part of a huge chain with both a corporate wired network and a wireless network. You've also connected to your company's VPN. Your routing table might look something like this:
Destination Netmask Interface Notes
----------- -------- --------- -----
Company email FFFFFF00 VPN Route ALL company traffic thru VPN
Wired network FFFF0000 Wired Traffic to other hotel addresses worldwide
Default 00000000 Wireless All other traffic
The most specific rule will route your company email safely through the VPN, even if the address happens to match the wired network also. All traffic to other addresses within the hotel chain will be routed through the wired network. And everything else will be sent through the wireless network.
* Actually, in every subnet, 2 of the addresses—the highest and the lowest—are reserved. The all-ones address is the broadcast address: this address sends data to every device on the subnet. And the all-zeroes address is used by a device to refer to itself when it doesn't yet have it's own IP address. I've ignored those for simplicity.
So the algorithm would be something like this:
initialize:
Sort routing table by netmask from most-specific to least specific.
Within each netmask, sort by IP address.
search:
foreach netmask {
Search IP addresses for (input & netmask) == (IP address & netmask)
Return corresponding interface if found
}
Return default interface
Ok so I this is what my structure and algorithm looks like now. It works and gives me the results that I want, however I still don't know how to sort ip addresses within netmasks. I used STL sort to sort the netmasks.
struct routeEntry_t
{
uint32_t ipAddr;
uint32_t netMask;
int interface;
bool operator<(const routeEntry_t& lhs) const
{
return lhs.netMask < netMask;
}
};
const int SIZE = 6;
routeEntry_t routing_table[SIZE];
void sorting()
{
//using STL sort from lib: algorithm
sort(routing_table, routing_table+SIZE);
}
int interface(uint32_t ipAddr)
{
for (int i = 0; i < SIZE; ++i)
{
if ((routing_table[i].ipAddr & routing_table[i].netMask) == (ipAddr & routing_table[i].netMask))
return routing_table[i].interface;
}
return routing_table[SIZE-1].interface;
}