개인 공부

NS-3 독학 - 3.Third.cc

Beige00 2024. 1. 12. 14:01

third.cc Topology

second.cc에서 {n0,n5,n6,n7}이 Wifi (10.1.3.0)으로 연결되어있는 구조가 추가되었다.

이를 구현해보겠다.

int
main(int argc, char* argv[])
{
    bool verbose = true;
    uint32_t nCsma = 3;
    uint32_t nWifi = 3;
    bool tracing = false;

    CommandLine cmd(__FILE__);
    cmd.AddValue("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
    cmd.AddValue("nWifi", "Number of wifi STA devices", nWifi);
    cmd.AddValue("verbose", "Tell echo applications to log if true", verbose);
    cmd.AddValue("tracing", "Enable pcap tracing", tracing);

    cmd.Parse(argc, argv);

    // The underlying restriction of 18 is due to the grid position
    // allocator's configuration; the grid layout will exceed the
    // bounding box if more than 18 nodes are provided.
    if (nWifi > 18)
    {
        std::cout << "nWifi should be 18 or less; otherwise grid layout exceeds the bounding box"
                  << std::endl;
        return 1;
    }

    if (verbose)
    {
        LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);
        LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);
    }

    NodeContainer p2pNodes;
    p2pNodes.Create(2);

    PointToPointHelper pointToPoint;
    pointToPoint.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
    pointToPoint.SetChannelAttribute("Delay", StringValue("2ms"));

    NetDeviceContainer p2pDevices;
    p2pDevices = pointToPoint.Install(p2pNodes);

    NodeContainer csmaNodes;
    csmaNodes.Add(p2pNodes.Get(1));
    csmaNodes.Create(nCsma);

    CsmaHelper csma;
    csma.SetChannelAttribute("DataRate", StringValue("100Mbps"));
    csma.SetChannelAttribute("Delay", TimeValue(NanoSeconds(6560)));

    NetDeviceContainer csmaDevices;
    csmaDevices = csma.Install(csmaNodes);

    NodeContainer wifiStaNodes;
    wifiStaNodes.Create(nWifi);
    NodeContainer wifiApNode = p2pNodes.Get(0);

    YansWifiChannelHelper channel = YansWifiChannelHelper::Default();
    YansWifiPhyHelper phy;
    phy.SetChannel(channel.Create());

    WifiMacHelper mac;
    Ssid ssid = Ssid("ns-3-ssid");

    WifiHelper wifi;

    NetDeviceContainer staDevices;
    mac.SetType("ns3::StaWifiMac", "Ssid", SsidValue(ssid), "ActiveProbing", BooleanValue(false));
    staDevices = wifi.Install(phy, mac, wifiStaNodes);

    NetDeviceContainer apDevices;
    mac.SetType("ns3::ApWifiMac", "Ssid", SsidValue(ssid));
    apDevices = wifi.Install(phy, mac, wifiApNode);

    MobilityHelper mobility;

    mobility.SetPositionAllocator("ns3::GridPositionAllocator",
                                  "MinX",
                                  DoubleValue(0.0),
                                  "MinY",
                                  DoubleValue(0.0),
                                  "DeltaX",
                                  DoubleValue(5.0),
                                  "DeltaY",
                                  DoubleValue(10.0),
                                  "GridWidth",
                                  UintegerValue(3),
                                  "LayoutType",
                                  StringValue("RowFirst"));

    mobility.SetMobilityModel("ns3::RandomWalk2dMobilityModel",
                              "Bounds",
                              RectangleValue(Rectangle(-50, 50, -50, 50)));
    mobility.Install(wifiStaNodes);

    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
    mobility.Install(wifiApNode);

    InternetStackHelper stack;
    stack.Install(csmaNodes);
    stack.Install(wifiApNode);
    stack.Install(wifiStaNodes);

    Ipv4AddressHelper address;

    address.SetBase("10.1.1.0", "255.255.255.0");
    Ipv4InterfaceContainer p2pInterfaces;
    p2pInterfaces = address.Assign(p2pDevices);

    address.SetBase("10.1.2.0", "255.255.255.0");
    Ipv4InterfaceContainer csmaInterfaces;
    csmaInterfaces = address.Assign(csmaDevices);

    address.SetBase("10.1.3.0", "255.255.255.0");
    address.Assign(staDevices);
    address.Assign(apDevices);

    UdpEchoServerHelper echoServer(9);

    ApplicationContainer serverApps = echoServer.Install(csmaNodes.Get(nCsma));
    serverApps.Start(Seconds(1.0));
    serverApps.Stop(Seconds(10.0));

    UdpEchoClientHelper echoClient(csmaInterfaces.GetAddress(nCsma), 9);
    echoClient.SetAttribute("MaxPackets", UintegerValue(1));
    echoClient.SetAttribute("Interval", TimeValue(Seconds(1.0)));
    echoClient.SetAttribute("PacketSize", UintegerValue(1024));

    ApplicationContainer clientApps = echoClient.Install(wifiStaNodes.Get(nWifi - 1));
    clientApps.Start(Seconds(2.0));
    clientApps.Stop(Seconds(10.0));

    Ipv4GlobalRoutingHelper::PopulateRoutingTables();

    Simulator::Stop(Seconds(10.0));

    if (tracing)
    {
        phy.SetPcapDataLinkType(WifiPhyHelper::DLT_IEEE802_11_RADIO);
        pointToPoint.EnablePcapAll("third");
        phy.EnablePcap("third", apDevices.Get(0));
        csma.EnablePcap("third", csmaDevices.Get(0), true);
    }

    Simulator::Run();
    Simulator::Destroy();
    return 0;
}

third.cc 전문이다.

(first.cc, second.cc와 중복되는 것은 자세한 설명을 생략함.)

 

1. bool verbose = true;
    uint32_t nCsma = 3;
    uint32_t nWifi = 3;
    bool tracing = false; :

verbose, nCsma는 second.cc에서 사용했다. nWifi 역시 Wifi 연결이 된 노드들을 표현하기 위한 변수인 것 같다.(n5,n6,n7)

tracing 이라는 boolean 변수를 false로 초기화 해준다.(PacketCapture를 할지 하지 않을 지 결정하는 bool 변수이다.)

 

2. CommandLine cmd(__FILE__);
    cmd.AddValue("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
    cmd.AddValue("nWifi", "Number of wifi STA devices", nWifi);
    cmd.AddValue("verbose", "Tell echo applications to log if true", verbose);
    cmd.AddValue("tracing", "Enable pcap tracing", tracing); 

    cmd.Parse(argc, argv); :

현재 변수 세팅 값을 cmd에 출력을 한다.

 

3.if (nWifi > 18)
    {
        std::cout << "nWifi should be 18 or less; otherwise grid layout exceeds the bounding box"
                  << std::endl;
        return 1;
    }

    if (verbose)
    {
        LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);
        LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);
    } :

Wifi에 연결되는 노드 갯수는 18개 이하로 제한한다.

그리고 verbose가 true일 때는 각 UdpEchomodel들의 LOG LEVEL을 INFO로 설정해준다.(enable)

 

4. NodeContainer p2pNodes;
    p2pNodes.Create(2); :

p2p로 연결될 n0,n1을 만들어준다.

 

5. PointToPointHelper pointToPoint;
    pointToPoint.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
    pointToPoint.SetChannelAttribute("Delay", StringValue("2ms"));

    NetDeviceContainer p2pDevices;
    p2pDevices = pointToPoint.Install(p2pNodes); :

p2p link setting 후 n0,n1 set p2pNodes에 설치.

 

6. NodeContainer csmaNodes;
    csmaNodes.Add(p2pNodes.Get(1));
    csmaNodes.Create(nCsma); :

Second.cc에 했던데로 n1을 csmaNodes에 추가하고 나머지 n2,n3,n4를 csmaNodes set에 추가한다.

 

7. CsmaHelper csma;
    csma.SetChannelAttribute("DataRate", StringValue("100Mbps"));
    csma.SetChannelAttribute("Delay", TimeValue(NanoSeconds(6560))); 

 

    NetDeviceContainer csmaDevices;
    csmaDevices = csma.Install(csmaNodes); :

LAN channel attribute setting & Install

 

8. NodeContainer wifiStaNodes;
    wifiStaNodes.Create(nWifi);
    NodeContainer wifiApNode = p2pNodes.Get(0); :

third.cc는 Wireless network가 포함되어있다. 따라서 wifi 연결이 될 node 5,6,7을 만들어준다.

그 후, wifi Access Point가 되어줄 node를 n0로 지정해준다.

 

9. YansWifiChannelHelper channel = YansWifiChannelHelper::Default();
    YansWifiPhyHelper phy;
    phy.SetChannel(channel.Create()); :

YansWifiChannelHelper는 ns-3 시뮬레이터에서 무선 채널을 설정하는 데 사용되는 클래스이다.

해당 클래스를 통해 전파 지연, 손실 등 무선 네트워크의 동작을 시뮬레이션이 가능하다.

YansWifiChannelHelper class channel을 Default로 초기화 해준다. 

 

YansWifiPhyHelper는 무선 물리 계층을 설정하는 데 사용되는 Helper 클래스이다.

해당 클래스를 통해 물리 계층에 적용할 무선 채널을 설정하거나 PCAP 트레이싱을 위해 데이터 링크 타입을 결정,

전송 오류율 모델 설정 등 다양한 무선 매개변수를 설정하는 데 사용 가능하다.

따라서 해당 코드는 YansWifiChannelHelper로부터 생성된 무선 채널을 YansWifiPhyHelper에 설정해주는 것이다.

 

10. WifiMacHelper mac;
      Ssid ssid = Ssid("ns-3-ssid");

      WifiHelper wifi;

     NetDeviceContainer staDevices;
     mac.SetType("ns3::StaWifiMac", "Ssid", SsidValue(ssid), "ActiveProbing", BooleanValue(false));
     staDevices = wifi.Install(phy, mac, wifiStaNodes);
:

이후 최종적으로 MacHelper, WifiHelper와 사용할 ssid를 정의하고, MacHelper를 초기화한다.

ns3::StaWifiMac은 Station, 클라이언트 역할의 Mac 계층을 세팅한 것이고, 

"Ssid", SsidValue(ssid) 를 통해 "ns-3-ssid"를 ssid로 지정해준다.

"ActiveProbing"은 이 클라이언트가 연결할 네트워크를 찾기 위해 주기적으로 스캔을 할지 여부를 결정하는데 사용되고,

이 값을 false로 주었으므로 클라이언트가 무선 네트워크를 찾을 때까지 기다리게 된다.

그 뒤 무선 네트워크 장치를 저장하기 위한 NetDeviceContainer, staDevices에  wifi 객체를 이용해 무선 네트워크의 노드에 대한 인터페이스를 생성하고 저장한다.

(무선 물리 계층, Mac 계층, 노드 set{n5,n6,n7}을 파라미터로 입력.)

 

11. NetDeviceContainer apDevices;
    mac.SetType("ns3::ApWifiMac", "Ssid", SsidValue(ssid));
    apDevices = wifi.Install(phy, mac, wifiApNode); :

10.에서 Station들의 Phy,Mac 계층 초기화를 통해 wifi를 설치하는 과정이 끝났다.

이제 AP로 작동할 n0에 대한 Mac 계층을 작성한다. ssid는 "ns-3-ssid" 그대로 사용하고, AP 역할의 MAC 계층을 세팅해준다.

그리고 구성된 wifi를 n0(wifiApNode)에 설치한다.

더보기
현재 구성된 시나리오

12.  MobilityHelper mobility;
    mobility.SetPositionAllocator("ns3::GridPositionAllocator",
                                  "MinX",
                                  DoubleValue(0.0),
                                  "MinY",
                                  DoubleValue(0.0),
                                  "DeltaX",
                                  DoubleValue(5.0),
                                  "DeltaY",
                                  DoubleValue(10.0),
                                  "GridWidth",
                                  UintegerValue(3),
                                  "LayoutType",
                                  StringValue("RowFirst")); :

무선 네트워크 연결을 가정했으므로, Wifi에 연결되는 host는 전부 MobileHost로 간주한다.

"ns3::GridPositionAllocator"를 사용해 노드의 초기 위치를 설정한다. 노드를 격자 형태로 배치하는 데 사용된다.

따라서 MinX, MinY 와 각 Cell간 간격(DeltaX, DeltaY), 가로 방향 cell 갯수(GridWidth),  LayoutType(RowFirst시 Row부터, ColumnFirst시 Col부터 노드 배치) 를 지정해줘야한다.

(여기서 GridWidth 값만 알면 총 노드 갯수 M/(GridWidthVal.)을 통해 GridHeight을 유추할 수 있다.)

 

13. mobility.SetMobilityModel("ns3::RandomWalk2dMobilityModel",
                              "Bounds",
                              RectangleValue(Rectangle(-50, 50, -50, 50)));
    mobility.Install(wifiStaNodes); :

MH model을 설정해줘야한다. Station node들에는 걸어다니는 사람을 가정해서 Model을 설정한다.

(RandomWalk2dMobilityModel : 무선 노드가 2차원 평면에서 랜덤하게 움직이는 모델)

"Bounds", Rectangle(-50,50,-50,50) 을 통해 각 변의 길이가 100인 정사각형에서 이동시킨다. (100m^2 공간을 가정한 것 같다.)

그 후에 해당 mobility model을 wifiStaion node들에게 설치한다.(n5,n6,n7)

 

14. mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
     mobility.Install(wifiApNode); :

ApNode(n0)는 AP이므로 고정시킨다.

 

15. InternetStackHelper stack;
    stack.Install(csmaNodes);
    stack.Install(wifiApNode);
    stack.Install(wifiStaNodes); :

각 노드 set 전부에 인터넷 스택을 설치한다.

 

16. Ipv4AddressHelper address;

    address.SetBase("10.1.1.0", "255.255.255.0");
    Ipv4InterfaceContainer p2pInterfaces;
    p2pInterfaces = address.Assign(p2pDevices);

    address.SetBase("10.1.2.0", "255.255.255.0");
    Ipv4InterfaceContainer csmaInterfaces;
    csmaInterfaces = address.Assign(csmaDevices);

    address.SetBase("10.1.3.0", "255.255.255.0");
    address.Assign(staDevices);
    address.Assign(apDevices); :

각 network(p2p, LAN, Wifi)에 할당될 IP를 지정해준다.

여기서 p2p, LAN은 Ipv4 Interface 를 통해 Ipv4 주소가 할당된 인터페이스들을 만드나,

Wifi Devices들은 직접 할당을 해주는 것에 유의하자.

 

17.  UdpEchoServerHelper echoServer(9);
    ApplicationContainer serverApps = echoServer.Install(csmaNodes.Get(nCsma));
    serverApps.Start(Seconds(1.0));
    serverApps.Stop(Seconds(10.0)); :

1초에 켜져서 10초에 꺼지는 Port 9 UdpEchoServer를 n4에 설치한다.(10.1.2.4)

 

18. UdpEchoClientHelper echoClient(csmaInterfaces.GetAddress(nCsma), 9);
    echoClient.SetAttribute("MaxPackets", UintegerValue(1));
    echoClient.SetAttribute("Interval", TimeValue(Seconds(1.0)));
    echoClient.SetAttribute("PacketSize", UintegerValue(1024)); :

    ApplicationContainer clientApps = echoClient.Install(wifiStaNodes.Get(nWifi - 1));
    clientApps.Start(Seconds(2.0));
    clientApps.Stop(Seconds(10.0)); 
:

2초에 시작해 10초에 꺼지는 n4에 연결될 UdpEchoClient를 구성하고 wifi연결이 되어있는 n7에 설치한다.

(10.1.3.3)

 

19.   Ipv4GlobalRoutingHelper::PopulateRoutingTables();

    Simulator::Stop(Seconds(10.0));

    if (tracing)
    {
        phy.SetPcapDataLinkType(WifiPhyHelper::DLT_IEEE802_11_RADIO);
        pointToPoint.EnablePcapAll("third");
        phy.EnablePcap("third", apDevices.Get(0));
        csma.EnablePcap("third", csmaDevices.Get(0), true);
    }

    Simulator::Run();
    Simulator::Destroy(); :
RoutingTable을 구성하고, 시뮬레이터가 중지될 시간을 10초로 세팅해준다.

왜냐하면 AP가 비콘 프레임을 계속 만들어내기 때문이다.

더보기

무선 네트워크에서 AP는 주기적으로 비콘 프레임을 전송하여 네트워크에 속한 노드들에게 자신의 존재를 알리고, 노드들은 이를 수신하여 네트워크에 참여한다. 이런 비콘 프레임은 네트워크 동작의 핵심 부분이며, 이 동작은 지속적으로 반복된다.

 

! 즉, 무선 네트워크 시뮬레이션에서는 AP가 지속적으로 동작하고 있는 상황이므로 명시적으로 시뮬레이션을 중지시켜줘야한다.

그 후, tracing이 켜져있다면 pcap을 생성한다. 

무선 IEEE 802.11 프레임을 캡처할 것이다. (Wifi)

P2P는 third의 이름으로 pcap을 생성할 것이며, n0에 대한 pcap, LAN의 첫번째 디바이스(n1)에 대한 pcap을 생성한다.

 


* 실행 결과(Tracing true로 설정하고 pcap을 tcpdump)

third.cc 실행결과

설정해둔대로 n4 UdpEchoServer로 UdpEchoClient가 설치된 n7이 Packet을 전송한다.

n4는 n7으로부터 패킷을 수신했으며, 다시 n7에게 reply packet을 전송한다.

 

third.cc pcap

third-0-0은 p2p link로써 캡처된 node 0,

third-0-1은 Wifi AP로써 캡처된 node 0,

third-1-0은 p2p link로써 캡처된 node 1,

third-1-1은 LAN(csma)로써 캡처된 node1일 것이다.

 

third-0-0

P2P link 상의 패킷들이 캡처되었다. AP를 통해 n6은 n4로 향했을 것이므로, n6 <-> n4 교환이 기록되어있다.

third-0-1.pcap

Link type이 IEEE802.11임을 볼 수 있고, 비콘 신호로 Wifi network를 유지시키는 것을 볼 수 있다. 이 수많은 패킷 교환 중 n6->n4가 일어난 과정을 찾아보자.

n4<->n6

Echo Client n7(10.1.3.3) ARP로 AP인 n0(10.1.3.4)의 위치를 찾기 위해 broadcast한다.

해당 Pcap은 apDevice.get(0) (node 0)에서 찍힌 것임을 감안해서 확인하자.

ARP로 n7(10.1.3.4)는 MAC 주소 00:00:00:00:00:0a에 있다고 Reply가 됐고, 이 후 n7은 n4에게로 UDP를 이용해 패킷을 전송했다.

그 다음에는 P2P link에도 찍혀있듯이 AP로써 packet을 받은 n0은 n1에게 데이터를 주고 이를 받은 n1은 LAN 망을 통해 n4(10.1.2.4)에 전송했을 것이다.

그 뒤에 n4는 반대의 과정으로 n7에게 reply를 쐇을 것이고, Wifi(10.1.3.0) 패킷 캡처본에는 n0에 도달한 reply 패킷이 n7으로 가는 과정이 찍혔을 것이다.

2.026083초의 기록을 보면 n1(10.1.3.4)가 10.1.3.3을 ARP로 찾고, 10.1.2.4에서 온 패킷을 전달해주는 것을 볼 수 있다.

 

third-1-0은 third-0-0과 같이 P2P link 캡처이므로 생략하고 third-1-1 캡처를 확인해보겠다.

third-1-1.pcap

AP로 작동한 n0이 P2P link로 n1에게 패킷을 주었고, ARP를 통해 n1(10.1.2.1)은 n4(10.1.2.4)를 찾는다. 이후 과정은 Second.cc와 동일.

'개인 공부' 카테고리의 다른 글

NS-3 독학 - 5.fifth.cc  (0) 2024.01.15
NS-3 독학 - 4.fourth.cc(Tracing)  (0) 2024.01.13
NS-3 독학 - 2. Second.cc  (0) 2024.01.11
NS-3 독학 - 1. First.cc  (0) 2024.01.11
NS-3 독학 - 0. 설치하기  (0) 2024.01.10