# NS2 網路模擬(以ubuntu實作) ### 此筆記分享 ![](https://i.imgur.com/DWGRuuF.png) ## 安裝 ```ubuntu= sudo apt-get update sudo apt-get install build-essential autoconf automake sudo apt-get install ns2 sudo apt-get install nam ``` > 更新軟體 > 安裝編譯C/C++軟件包 > 安裝NS2套件 > 安裝NAM套件 ## 建立TCL檔案並撰寫 ```ubuntu= sudo pico xxx.tcl ``` ## 產生一個模擬的物件 ```ubuntu= set ns [new Simulator] ``` ## 針對不同的資料流定義不同的顏色給NAM用 ```ubuntu= $ns color 1 Blue $ns color 2 Red ``` > TCP藍色 UDP紅色 ## 開啟一個NAM trace file寫入到w中 ```ubuntu= set nf [open out.nam w] ``` ## 使用NAM觀察動態模擬過程時,就要使用這個指令 ```ubuntu= $ns namtrace-all $nf ``` > 這指令就是把相關的事件記錄到out.nam ## 定義一個結束的程序 > 這個finish只是當模擬結束後,需要把資料完全寫入到記錄檔 ```ubuntu= proc finish {} { global ns nf $ns flush-trace # 關閉 close $nf # 在trace-file上執行Nam # 以背景執行的方式去執行NAM exec nam out.nam & exit 0 } ``` ## 產生四個網路節點 ```ubuntu= set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] ``` ## 節點連接 ```ubuntu= $ns duplex-link $n0 $n2 2Mb 10ms DropTail $ns duplex-link $n1 $n2 2Mb 10ms DropTail $ns duplex-link $n2 $n3 1.7Mb 20ms DropTail ``` > 連線速率(Mb)延遲(ms)DropTail(排隊方式DropTail的Link) ## 設定n2到n3之間的Queue Size為10個封包大小 ```ubuntu= $ns queue-limit $n2 $n3 10 ``` > n2到n3是一個bottleneck 所以才要設定他中間queue的大小 > bottleneck : 流量高的地方 ## 設定節點的位置給NAM用 ```ubuntu= $ns duplex-link-op $n0 $n2 orient right-down $ns duplex-link-op $n1 $n2 orient right-up $ns duplex-link-op $n2 $n3 orient right ``` ## 觀測n2到n3之間queue的變化給NAM用 ```ubuntu= $ns duplex-link-op $n2 $n3 queuePos 0.5 ``` ## 建立一條TCP的連線 ```ubuntu= set tcp [new Agent/TCP] ``` >補充:建立一個TCP Tahoe的傳送端,建立完後把它指派給名稱為tcp ## 允許區分多個流 ```ubuntu= $tcp set class_ 2 ``` >剛定義兩種顏色,就是分為兩個流 ## 設定sink是指接收的那端走TCP連線,並建立一個 new Agent ```ubuntu= $ns attach-agent $n0 $tcp set sink [new Agent/TCPSink] ``` >剛建立了一個TCP Tahoe的傳送端,現要設定一個接收端來接收由傳送端送過來的資料,並回應Ack ## 把n3和新的Agent連在一起,讓n3使用sink接收 ```ubuntu= $ns attach-agent $n3 $sink ``` >意思就是說:node n3上會跑TCPSink接收端程式 ## 把tcp 和sink相連接 ```ubuntu= $ns connect $tcp $sink ``` ## 在NAM中,TCP的連線會以藍色表示 ```ubuntu= $tcp set fid_ 1 ``` >設定flow id為1 也就是TCP為藍線 ## 在TCP連線之上建立FTP應用程式 ```ubuntu= set ftp [new Application/FTP] $ftp attach-agent $tcp $ftp set type_ FTP ``` ## 建立一條UDP的連線 ```ubuntu= set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n3 $null $ns connect $udp $null $udp set fid_ 2 ``` >最後行fid_2 也就是UDP為紅線 ## 在UDP連線之上建立CBR應用程式 ```ubuntu= set cbr [new Application/Traffic/CBR] $cbr attach-agent $udp $cbr set type_ CBR $cbr set packet_size_ 1000 $cbr set rate_ 1mb $cbr set random_ false ``` ## 設定FTP和CBR資料傳送開始和結束時間 ```ubuntu= $ns at 0.1 "$cbr start" $ns at 1.0 "$ftp start" $ns at 4.0 "$ftp stop" $ns at 4.5 "$cbr stop" ``` ## 結束TCP的連線(不一定需要寫來結束連線) ```ubuntu= $ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink" ``` ## 在模擬環境中,5秒後去呼叫finish來結束模擬(5秒並不一定等於實際模擬的時間) ```ubuntu= $ns at 5.0 "finish" ``` ## 執行模擬 ```ubuntu= $ns run ``` ## 執行TCL檔案 ```ubuntu= ns ***.tcl ```