On a recent project it became necessary to be able to route certain IP traffic via a specified network adapter. Although rather involved this is not as hard as it may first seem. On a desktop this would be achieved by changing the IP routing tables using the ROUTE command, but how do you do this programmatically on a handheld?
First it is necessary to find the IP address, gateway address and interface index of the adapter that you wish to route over. This information can easily be obtained by calling GetAdapterAddresses() a number of times to enumerate all network device data.
Once the IP information has been obtained for the selected adapter then CreateIpForwardEntry() can be called to setup the route. The CreateIpForwardEntry() API takes a PMIB_IPFORWARDROW parameter essentially a route definition. This needs to be setup as follows:
- dwForwardDest - Set to the IP address of server you will be connecting too.
- dwForwardMask - Mapping IP address mask. This will need to be 255.255.255.255 for specified traffic.
- dwForwardPolicy - Set to zero.
- dwForwardNextHop - This needs to be set to the discovered IP adapters gateway address.
- dwForwardIfIndex - This needs to be set to the discovered IP adapters index.
- dwForwardType - This is set to MIB_IPROUTE_TYPE_INDIRECT.
- dwForwardProto - This is set to MIB_IPPROTO_NETMGMT.
- dwForwardAge - Set to zero.
- dwForwardNextHopAS - Set to zero.
- dwForwardMetric1 - Set to 1.
- dwForwardMetric2-5 - Set to 0xFFFFFFFF.
It is now possible to simply use sockets to connect to the server or service that you specified in the dwForwardDest. All IP traffic over this socket will be directed via the adapter that was specified.
At the end of the session the DeleteIpForwardEntry() API should be called to tear down the route.