This has only been tested with the UM-OLSR routing protocol.
We change our script so that the addresses of the receiving nodes to be identical, and not equal to either of the nodes:

set node_(40) [$ns_ node 42]
$node_(40) random-motion 0
set node_(41) [$ns_ node 42]
$node_(41) random-motion 0

Now we can establish a flow to one of the nodes 40 or 41, and the packets will reach the nearer of the two, based on the routing table of each node.

To avoid ns-2 error, we need to comment two lines in the ns2/classifier/classifier.cc and ns2/classifier/classifier-addr.cc files (Changes in bold face):
classifier.cc:

NsObject* Classifier::find(Packet* p)
{
NsObject* node = NULL;
int cl = classify(p);
if (cl = nslot_ || (node = slot_[cl]) == 0) {
if (default_target_)
return default_target_;
/*
* Sigh. Can't pass the pkt out to tcl because it's
* not an object.
*/

// Tcl::instance().evalf("%s no-slot %ld", name(), cl);
if (cl == TWICE) {
/*
* Try again. Maybe callback patched up the table.
*/
cl = classify(p);
if (cl = nslot_ || (node = slot_[cl]) == 0)
return (NULL);
}
}
return (node);
}

classifier-addr.cc:

NsObject* BcastAddressClassifier::find(Packet* p)
{
NsObject* node = NULL;
int cl = classify(p);
if (cl = nslot_ || (node = slot_[cl]) == 0) {
if (cl == BCAST_ADDR_MASK) {
// limited broadcast; assuming no such packet
// would be delivered back to sender
return bcast_recver_;
}
if (default_target_)
return default_target_;

/*
* Sigh. Can't pass the pkt out to tcl because it's
* not an object.
*/

// Tcl::instance().evalf("%s no-slot %d", name(), cl);
/*
* Try again. Maybe callback patched up the table.
*/
cl = classify(p);
if (cl = nslot_ || (node = slot_[cl]) == 0)
return (NULL);
}

return (node);
}

Advertisements