FetchingIPAddresses

From Nsnam
Jump to: navigation, search

Grabbing the IP addresses associated with a node is a relatively simple task. Much like a normal computer and operating system, each node may have NetDevices, which may be associated with IP interface objects. The latter are hidden from typical user programs behind IPv4 objects. From there, you may query for devices and interfaces associated with the node, the IP address bound to interfaces, etc. The following loop prints all IP addresses for all nodes, excluding the local loopback interfaces.

  Ipv4Address loopback("127.0.0.1");

  for (NodeList::Iterator iter = NodeList::Begin();
       iter != NodeList::End();
       iter++) {
    Ptr<Node> node = (*iter);

    Ptr<Ipv4> ipv4 = node->GetObject<Ipv4>();
    NS_ASSERT(ipv4 != 0);
    
    for (uint32_t index = 0; index < ipv4->GetNInterfaces(); index++) {
      Ipv4Address ipv4Address = ipv4->GetAddress(index);

      if (ipv4Address != loopback) {
        std::cout << " node " << node->GetId() <<
          " ip " << ipv4Address << std::endl;
      }
      // end iterating over interfaces
    }

    // end iterate over nodes
  }