Get Current node IP Address

217 views
Skip to first unread message

Hassam Mughal

unread,
Mar 12, 2020, 9:45:52 AM3/12/20
to ns-3-users
I am trying to access the IP Address of my current node in the Phy MonitorSnifferRx Trace source method from the packet received. As this method doesn't have a socket in the parameter. So how can I extract the current node IP Address?
I tried to use GetObject method for Ptr<Ipv4> and Ptr<Node> like this:
Ptr<Node> node = this->GetObject<Node>();
but it is not supporting this even.

Any help or guidance in this regard will be highly appreciated. Thanks

Hassam Mughal

unread,
Mar 14, 2020, 2:20:07 PM3/14/20
to ns-3-users
Can anyone please help me for this?

Jay Vivarekar

unread,
Mar 15, 2020, 2:33:09 AM3/15/20
to ns-3-users
Hi.
If you could provide a more-detailed description of your problem, it will be much easier to provide a solution. For example, is this issue related to a built-in module of NS-3? Or is it a custom module? Just specifying the trace source method doesn't provide much information. It would be better if you could post a snippet of the relevant section of the code.

Jay Vivarekar

Hassam Mughal

unread,
Mar 15, 2020, 3:57:41 AM3/15/20
to ns-3-users
Hi Jay,
A bundle of thanks for responding. It is related to built-in module. What I need is, whenever a packet is received by any node, I want to get the IP Address of the node that has received that packet. I am able to get the node's own IP address in the receive packet method, however as u know that the RX trace is triggered before the receive packet. So, I need to actually get the node's IP Address in the trace method so that I can add this to a custom table that I am creating. The code snippet for the RX trace is as follows;

void
RoutingExperiment::Rx (std::string context, Ptr <const Packet> packet, uint16_t channelFreqMhz,  WifiTxVector txVector, MpduInfo aMpdu, SignalNoiseDbm signalNoise){
        //context will include info about the source of this event. Use string manipulation if you want to extract info.
        //std::cout << BOLD_CODE <<  context << END_CODE << std::endl;
        //Print the info.
        //      Packet::EnablePrinting();
        //              Packet::EnableChecking();
        //      packet->Print(std::cout << "\nTime: " << Simulator::Now().GetSeconds() << "s, Packet Details are: ");
        Ipv4Address src_ip = GetSourceAddress(packet);
        Ipv4Address des_ip = GetDestAddress(packet);    if(packet->GetSize() >= 500){
                counterAppRX++; } else {
                counterRX++;
        }       NS_LOG_DEBUG(m_mainAddressW << " W Received Packet from Source Address: " << src_ip << ", With Destination address in Packet: " << des_ip
                        << ", \nSize = " << packet->GetSize()
                        << " Freq = "<<channelFreqMhz
                        << " Mode = " << txVector.GetMode()
                        << " ReceptionDataRate = " << txVector.GetMode().GetDataRate(txVector)
                        << " RX Counter: " << counterRX << "\t RX APP Counter: " << counterAppRX);
        m_rxDataRate = txVector.GetMode().GetDataRate(txVector)/1000000;        //insert into table     if(src_ip == Ipv4Address("102.102.102.102") || des_ip == Ipv4Address("102.102.102.102"))
        {
                NS_LOG_DEBUG("This is RTS/CTS/ACK Packet!");
        }
        else
        {
                RTableEntry rTableEntryW;
                bool permanentTableVerifier = m_rTableW.LookupRoute (src_ip, rTableEntryW);    //m_rTableW is the object of rTable class
                NS_LOG_DEBUG("Is the route inside the table? " << permanentTableVerifier);
                if (permanentTableVerifier == false)
                {
                        NS_LOG_DEBUG ("Received New WRoute!");
                        RTableEntry newEntry(/*My Address=*/ src_ip, /*destination address=*/ des_ip, /*source address=*/src_ip, /*current location=*/ "L2",
                        /*previous location=*/ "L1", /*time connected=*/Simulator::Now (), /*time last pakcet received=*/ Simulator::Now (), /*time first packet received*/
                        Simulator::Now ());
                        m_rTableW.AddRoute (newEntry);
                        NS_LOG_DEBUG ("New WRoute added to Wtable!");
                }
                else
                {
                        rTableEntryW.setMyAddress(m_mainAddressW);
                        rTableEntryW.setDestAddress(des_ip);
                        rTableEntryW.setSourceAddress(src_ip);
                        rTableEntryW.setCurrLocation("L2");
                        rTableEntryW.setLastLocation("L1");
                        rTableEntryW.setTimeConnected(Simulator::Now());
                        rTableEntryW.setTimeLastPktRcvd(Simulator::Now());
                        rTableEntryW.setTimeFirstPktRcvd(Simulator::Now());
                        m_rTableW.Update(rTableEntryW);
                        NS_LOG_DEBUG ("Route Updated in WTable!");
                }
        }       NS_LOG_DEBUG("Values in the rTableW are: ");
                if(m_rTableW.RTableSize() > 0)
                {
                        m_rTableW.GetListOfAllRoutes();
                }
                else
                {
                        NS_LOG_DEBUG("RTableW is Empty!");
                }       //We can also examine the WifiMacHeader
        WifiMacHeader hdr;
        if (packet->PeekHeader(hdr))
        {
                NS_LOG_DEBUG("\tDestination MAC : " << hdr.GetAddr1() << "\tSource MAC : " << hdr.GetAddr2());
        }
}

Hassam Mughal

unread,
Mar 15, 2020, 4:01:20 AM3/15/20
to ns-3-users
void
RoutingExperiment::Rx (std::string context, Ptr <const Packet> packet, uint16_t channelFreqMhz, WifiTxVector txVector, MpduInfo aMpdu, SignalNoiseDbm signalNoise){
 
//context will include info about the source of this event. Use string manipulation if you want to extract info.
 
//std::cout << BOLD_CODE << context << END_CODE << std::endl;
 
//Print the info.
 
// Packet::EnablePrinting();
 
// Packet::EnableChecking();
 
// packet->Print(std::cout << "\nTime: " << Simulator::Now().GetSeconds() << "s, Packet Details are: ");
 
Ipv4Address src_ip = GetSourceAddress(packet);
 
Ipv4Address des_ip = GetDestAddress(packet); if(packet->GetSize() >= 500){
 counterAppRX
++; } else {
 counterRX
++;
 
} NS_LOG_DEBUG(m_mainAddressW << " W Received Packet from Source Address: " << src_ip << ", With Destination address in Packet: " << des_ip
 
<< ", \nSize = " << packet->GetSize()
 
<< " Freq = "<<channelFreqMhz
 
<< " Mode = " << txVector.GetMode()
 
<< " ReceptionDataRate = " << txVector.GetMode().GetDataRate(txVector)
 
<< " RX Counter: " << counterRX << "\t RX APP Counter: " << counterAppRX);
 m_rxDataRate
= txVector.GetMode().GetDataRate(txVector)/1000000; //insert into table if(src_ip == Ipv4Address("102.102.102.102") || des_ip == Ipv4Address("102.102.102.102"))
 
{
 NS_LOG_DEBUG
("This is RTS/CTS/ACK Packet!");
 
}
 
else
 
{
 
RTableEntry rTableEntryW;
 
bool permanentTableVerifier = m_rTableW.LookupRoute (src_ip, rTableEntryW);

 NS_LOG_DEBUG
("Is the route inside the table? " << permanentTableVerifier);
 
if (permanentTableVerifier == false)
 
{
 NS_LOG_DEBUG
("Received New WRoute!");
 
RTableEntry newEntry(/*My Address=*/ src_ip, /*destination address=*/ des_ip, /*source address=*/src_ip, /*current location=*/ "L2",
 
/*previous location=*/ "L1", /*time connected=*/Simulator::Now (), /*time last pakcet received=*/ Simulator::Now (), /*time first packet received*/
 
Simulator::Now ());
 m_rTableW
.AddRoute (newEntry);
 NS_LOG_DEBUG
("New WRoute added to Wtable!");
 
}
 
else
 
{
 rTableEntryW
.setMyAddress(m_mainAddressW);
 rTableEntryW
.setDestAddress(des_ip);
 rTableEntryW
.setSourceAddress(src_ip);
 rTableEntryW
.setCurrLocation("L2");
 rTableEntryW
.setLastLocation("L1");
 rTableEntryW
.setTimeConnected(Simulator::Now());
 rTableEntryW
.setTimeLastPktRcvd(Simulator::Now());
 rTableEntryW
.setTimeFirstPktRcvd(Simulator::Now());
 m_rTableW
.Update(rTableEntryW);
 NS_LOG_DEBUG
("Route Updated in WTable!");
 
}
 
} NS_LOG_DEBUG("Values in the rTableW are: ");
 
if(m_rTableW.RTableSize() > 0)
 
{

 m_rTableW
.GetListOfAllRoutes(); //print the table contents

 
}
 
else
 
{
 NS_LOG_DEBUG
("RTableW is Empty!");
 
} //We can also examine the WifiMacHeader
 
WifiMacHeader hdr;
 
if (packet->PeekHeader(hdr))
 
{
 NS_LOG_DEBUG
("\tDestination MAC : " << hdr.GetAddr1() << "\tSource MAC : " << hdr.GetAddr2());
 
}
}



On Sunday, March 15, 2020 at 3:33:09 PM UTC+9, Jay Vivarekar wrote:

Hassam Mughal

unread,
Mar 15, 2020, 4:11:16 AM3/15/20
to ns-3-users
The code for PrintReceivedPacket is as follows; As you can see, in this method we have the socket, so we can easily get the node's own ip address, but in the RX trace source method, we don't have the socket. Hence, how can I get the node's ip address?

static inline std::string
PrintReceivedPacket (Ptr<Socket> socket, Ptr<Packet> packet, Address senderAddress)
{
        std
::ostringstream oss; //  oss << Simulator::Nowdsdv.PrintRoutingTableAllAt (rtt, rtw); ().GetSeconds () << " " << socket->GetNode ()->GetId ();
       
Ptr<Node> node = socket->GetNode();
       
Ptr<Ipv4> ip = node->GetObject<Ipv4>();
       
Ipv4Address address = ip->GetAddress(1,0).GetLocal();
       
if (InetSocketAddress::IsMatchingType (senderAddress))
       
{
               
InetSocketAddress addr = InetSocketAddress::ConvertFrom (senderAddress);
                oss
<< Simulator::Now ().GetSeconds () << " , Node: " << node->GetId() << ", Address: " << address << " received one packet from " << addr.GetIpv4 ();
       
}
       
else
       
{
                oss
<< Simulator::Now ().GetSeconds () << " received one packet!";
       
}
       
return oss.str ();
}





On Sunday, March 15, 2020 at 3:33:09 PM UTC+9, Jay Vivarekar wrote:

Adil Alsuhaim

unread,
Mar 15, 2020, 1:11:56 PM3/15/20
to ns-3-users
If by "current node" you mean the node that fired the MonitorSnifferRx trace?

You have the context string, which would be be like "/NodeList/4/DeviceList/..." if the node that fired MonitorSnifferRx is 4. Use string manipulation or regular expression to extract the node ID from the context string, and convert it to integer, let's call it node_id. Once you have done that, then you can try the following code to extract the IPv4 address:

Ptr<Node> node = NodeList::GetNode (node_id);
Ptr<NetDevice> dev = node->GetDevice(0); // assuming only one device. Loop through devices if needed
Ptr<Ipv4> ip = node->GetObject<Ipv4>(); // Get Ipv4 Object
uint32_t interfaceId = ip->GetInterfaceForDevice(dev); //Get interface id
Ipv4InterfaceAddress addrI = ip->GetAddress(interfaceId, 0); //address index 0, might be different
Ipv4Address ip_addr = addrI.GetLocal();

Note that node->GetObject<Ipv4>() would return null if no such object exist, so make sure you already installed IPs to nodes.

Cheers,
Adil

Jay Vivarekar

unread,
Mar 16, 2020, 12:53:56 AM3/16/20
to ns-3-users
Hello.
I think the solution by Adil Alsuhaim is what you are looking for.

Jay Vivarekar

Hassam Mughal

unread,
Mar 16, 2020, 4:13:52 AM3/16/20
to ns-3-users
Dear Adil,

Thanks a ton. I am trying your suggested solution and will get back to you in a while. I hope it works as it seems the only solution.
Thanks a lot

Hassam Mughal

unread,
Mar 16, 2020, 4:15:37 AM3/16/20
to ns-3-users
Yes, I am trying his solution. Let's hope it works :)

Hassam Mughal

unread,
Mar 16, 2020, 8:13:57 AM3/16/20
to ns-3-users
Thank you soo much! It is working perfectly! You are a life saviour!


On Monday, March 16, 2020 at 2:11:56 AM UTC+9, Adil Alsuhaim wrote:

Edivaldo

unread,
May 8, 2020, 1:37:29 AM5/8/20
to ns-3-users
Hi, Hassam.
I hope you're well.

Could you please help me with the two topics below NS 3?


In summary I need to analyze ARP packets and check IPs and MAC sources / destinations.

For the guidance of Mr. Adil (very attentive and intelligent boy), you added this code:
Ptr <Node> node = NodeList :: GetNode (node_id);
    Ptr <NetDevice> dev = node-> GetDevice (0); // assuming only one device. Loop through devices if needed
    Ptr <Ipv4> ip = node-> GetObject <Ipv4> (); // Get Ipv4 Object
    uint32_t interfaceId = ip-> GetInterfaceForDevice (dev); // Get interface id
    Ipv4InterfaceAddress addrI = ip-> GetAddress (interfaceId, 0); // address index 0, might be different
    Ipv4Address ip_addr = addrI.GetLocal ();

Please, which of these functions this code was included?

- static inline std :: string
PrintReceivedPacket (Ptr <Socket> socket, Ptr <Packet> packet, Address senderAddres

- void
RoutingExperiment :: Rx (std :: string context, Ptr <const Packet> packet, uint16_t channelFreqMhz, WifiTxVector txVector, MpduInfo aMpdu, SignalNoiseDbm signalNoise) {

Thank in advance for your help and attention.

Health and peace.

Best regards,
Edivaldo

Hassam Mughal

unread,
May 9, 2020, 4:31:18 AM5/9/20
to ns-3-users
Hello Edivaldo,

Apologies for late response. Kindly use the below code in order to get the IP Address at any layer. Moreover, IP address of acknowledgement and other control packets is not possible.

Ipv4Address RoutingExperiment::GetSourceAddress(Ptr<const Packet> p)
{
Ipv4Address src;
// To get a header from Ptr<Packet> packet first, copy the packet
Ptr<Packet> q = p->Copy();
// Use indicator to search the packet
PacketMetadata::ItemIterator metadataIterator = q->BeginItem();
PacketMetadata::Item item;
while (metadataIterator.HasNext())
{
item = metadataIterator.Next();
NS_LOG_FUNCTION("item name: " << item.tid.GetName());
// If we want to have a dsdv header
if(item.tid.GetName() == "ns3::Ipv4Header")
{
Callback<ObjectBase *> constr = item.tid.GetConstructor();
NS_ASSERT(!constr.IsNull());
// Ptr<> and DynamicCast<> won't work here as all headers are from ObjectBase, not Object
ObjectBase *instance = constr();
NS_ASSERT(instance != 0);
Ipv4Header* ipv4Header = dynamic_cast<Ipv4Header*>(instance);
NS_ASSERT(ipv4Header != 0);
ipv4Header->Deserialize(item.current);
src = ipv4Header->GetSource();
NS_LOG_DEBUG("Source IP ADDRESS FOUND from IPV4Header: " << src);
break;
}
else if(item.tid.GetName() == "ns3::ArpHeader")
{
Callback<ObjectBase *> constr = item.tid.GetConstructor();
NS_ASSERT(!constr.IsNull());
// Ptr<> and DynamicCast<> won't work here as all headers are from ObjectBase, not Object
ObjectBase *instance = constr();
NS_ASSERT(instance != 0);
ArpHeader* arpHeader = dynamic_cast<ArpHeader*>(instance);
NS_ASSERT(arpHeader != 0);
arpHeader->Deserialize(item.current);
src = arpHeader->GetSourceIpv4Address();
NS_LOG_DEBUG("Source IP ADDRESS FOUND from ARPHeader: " << src);
break;
}
else
{
NS_LOG_DEBUG("NO SOURCE IP ADDRESS FOUND");
//break;
}
}
return src;
}


I hope this helps.
Cheers.
Hassam

Hassam Mughal

unread,
May 9, 2020, 4:32:10 AM5/9/20
to ns-3-users
Moreover, the functions I used this is in both receivedPacket as well as RX trace source methods,


On Friday, May 8, 2020 at 2:37:29 PM UTC+9, Edivaldo wrote:

Urutago

unread,
May 9, 2020, 4:26:10 PM5/9/20
to ns-3-...@googlegroups.com
Hello, Hassam.

No problem! Thank you very much for your attention and return of my doubt.

I am also following the guidelines of the great expert Adil, as he guided us on these topics.

Health and peace.

Sincerely,
Edivaldo

--
Posting to this group should follow these guidelines https://www.nsnam.org/wiki/Ns-3-users-guidelines-for-posting
---
You received this message because you are subscribed to a topic in the Google Groups "ns-3-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ns-3-users/0u4a7GQMns0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ns-3-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ns-3-users/b65b55a3-c3b6-402a-9aa9-7d4de21a4ad7%40googlegroups.com.

Edivaldo

unread,
May 14, 2020, 3:29:37 PM5/14/20
to ns-3-users
Hi, Hassam!
I hope everything is at peace. I verified in the part of this code, as I listed here, that you use a table.

{
                RTableEntry rTableEntryW;
                bool permanentTableVerifier = m_rTableW.LookupRoute (src_ip, rTableEntryW);    //m_rTableW is the object of rTable class
                NS_LOG_DEBUG("Is the route inside the table? " << permanentTableVerifier);
                if (permanentTableVerifier == false)
                {
                        NS_LOG_DEBUG ("Received New WRoute!");
                        RTableEntry newEntry(/*My Address=*/ src_ip, /*destination address=*/ des_ip, /*source address=*/src_ip, /*current location=*/ "L2",
                        /*previous location=*/ "L1", /*time connected=*/Simulator::Now (), /*time last pakcet received=*/ Simulator::Now (), /*time first packet received*/
                        Simulator::Now ());
                        m_rTableW.AddRoute (newEntry);
                        NS_LOG_DEBUG ("New WRoute added to Wtable!");
                }
                else
                {
                        rTableEntryW.setMyAddress(m_mainAddressW);
                        rTableEntryW.setDestAddress(des_ip);
                        rTableEntryW.setSourceAddress(src_ip);
                        rTableEntryW.setCurrLocation("L2");
                        rTableEntryW.setLastLocation("L1");
                        rTableEntryW.setTimeConnected(Simulator::Now());
                        rTableEntryW.setTimeLastPktRcvd(Simulator::Now());
                        rTableEntryW.setTimeFirstPktRcvd(Simulator::Now());
                        m_rTableW.Update(rTableEntryW);
                        NS_LOG_DEBUG ("Route Updated in WTable!");
                }

My system should implement a table that stores nodes that have been identified as malicious. And then I would like to export the table to a log file.

Please, is this procedure you performed the way for me to do this routine?


Thank you very much.

Health and peace.
Edivaldo


Hassam Mughal

unread,
May 14, 2020, 3:38:05 PM5/14/20
to ns-3-...@googlegroups.com
Hello Edivaldo,

In my case, I was creating a table using the RX trace. If you aim to do similar approach then you can use this way, or there is a much cleaner way to do that and that is to create your custom application and pass the parameters in a header which identifies the node is malicious or not and then create a table in your application class or in your main class.
Thanks

--
Posting to this group should follow these guidelines https://www.nsnam.org/wiki/Ns-3-users-guidelines-for-posting
---
You received this message because you are subscribed to a topic in the Google Groups "ns-3-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ns-3-users/0u4a7GQMns0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ns-3-users+...@googlegroups.com.

Urutago

unread,
May 14, 2020, 7:49:00 PM5/14/20
to ns-3-...@googlegroups.com
I'm working on the ArpHeader module.

In which I am analyzing the existence of anomalies in ARP requests (Req). If a malicious node is detected, it must be saved in a reputation list (or maybe tabela).

So the other nodes will be able to consult it and identify which nodes are marked as malicious in that list (table).

To obtain the information (IP and MACs origin and destination) I am using the code below, as our great and intelligent friend Adil sent us:

LlcSnapHeader llc;
if (p-> PeekHeader (llc)) // succeeds if packet has the header
{
     if (llc.GetType () == 0x0806)
     {

         // this is an ARP packet, you can try to peek ArpHeader, or do what you need to do
     }
     else if (llc.GetType () == 0x0800)
     {
         // This is an IPv4 packet
     }
}

Thank you for your feedback and attention.

Edivaldo

Hassam Mughal

unread,
May 14, 2020, 11:53:06 PM5/14/20
to ns-3-users
Ahan that's great. Yes, in such case you can consider my approach.
To unsubscribe from this group and all its topics, send an email to ns-3-...@googlegroups.com.

--
Posting to this group should follow these guidelines https://www.nsnam.org/wiki/Ns-3-users-guidelines-for-posting
---
You received this message because you are subscribed to a topic in the Google Groups "ns-3-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ns-3-users/0u4a7GQMns0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ns-3-...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages