How do I get the node ID/source node of the packet?

136 views
Skip to first unread message

Shey Janota

unread,
Mar 27, 2023, 5:28:27 PM3/27/23
to ns-3-users
Hi everyone!

I would like to know which node transmitted a packet, by obtaining the node ID or the source node of a packet.

How do I implement it? 

Tommaso Pecorella

unread,
Mar 28, 2023, 1:17:13 AM3/28/23
to ns-3-users
Hi,

hard (if not impossible). One way is to look at the source IP address (hopefully you have it in the packet), and then find the node that has that IP address.
Personally I'd simply use the IP address, which is fairly ok unless you have a node with multiple IP addresses.
If you really want the NodeId, you can iterate though the NodeList:
for (NodeList::Iterator it = NodeList::Begin(); it != NodeList::End(); ++it) {}

and look for the IP addresses owned by the node. It's not super-fast but it will do.

Hassan Zeb

unread,
Mar 28, 2023, 2:36:54 AM3/28/23
to ns-3-users
It is very simple check this code
////////////////when you have socket in your function 
Ptr<Node> n1 =socket->GetNode();
uint32_t id = socket->GetNode ()->GetId();
 Ptr<Ipv4> ipv4 = n1->GetObject<Ipv4> ();
 Ipv4InterfaceAddress iaddr = ipv4->GetAddress (1,0);
 Ipv4Address source = iaddr.GetLocal (); 
The  uint32_t id is the id of node, source is the ip address now use std::cout<< to get the desired information for example

std::cout<<"my id is "<<id<<" and ip is "<<source <<" sending packet"<<std::endl


Tommaso Pecorella

unread,
Mar 28, 2023, 4:26:48 AM3/28/23
to ns-3-users
@Hassan's code is correct, but it works only for packets sent by a node, not for packets received by another node.

Moreover, mind the following pitfalls:
  1. ipv4->GetAddress (1,0); will fetch the 1st address for the 2nd interface (the 1st one is the loopback, whose address is 127.0.0.1). Mind that a node can have multiple interfaces and each interface can have multiple addresses.
  2. There's also IPv6 (but the code is similar).
A more robust solution would iterate through all the addresses on all the interfaces:
for (auto ifIndex = 0; ifIndex < ipv4->GetNInterfaces(); ifIndex++)
{
  for  (auto addrIndex = 0; addrIndex < ipv4->GetNAddresses(ifIndex); addrIndex++)
  {
    Ipv4InterfaceAddress iaddr = ipv4->GetAddress (ifIndex, addrIndex);
    Ipv4Address source = iaddr.GetAddress ();
  }
}

BTW, please use "GetAddress" instead of "GetLocal". Sooner or later I'll deprecate GetLocal.

Shey Janota

unread,
Mar 29, 2023, 2:09:06 PM3/29/23
to ns-3-users
Hello guys!

Thanks very much for your help and support with this doubt of mine.



Best Regards.

Sheila Janota.

Reply all
Reply to author
Forward
0 new messages