NS2是一種高效的網路模擬器,在網路的協議開發,網路效能評估以及網路故障排除方面有著廣泛的應用。NS2主要用於科學研究,是一款開源軟體。NS2在網路研究相關論文撰寫,實際工程建模評估等過程中起著關鍵作用。其他類似的網路模擬軟體還有OPNET等。
NS2可以在Linux平臺下執行,也可以在Windows下的通過Linux模擬器來執行。NS2的使用以及安裝對於不熟悉Linux作業系統、未接觸過tcl、Otcl的同學來說有一定的難度。本教程希望通過一個簡單的關於TCP和UDP的模擬程式帶領大家進行入門學習。
工具/原料
安裝有ns2-2.35的centOS6.0系統
gedit編輯器
方法/步驟
第一步:驗證NS2模擬環境
本教程的環境為centOS6.0+NS2 2.35。關於Linux以及NS2的安裝已經有大量的優秀教程,希望小夥伴可以查詢相關資料配置好基本的執行環境。
驗證方法如下:找到NS2的安裝路徑,並找到~/ns-2.35/tcl/ex資料夾下的simple.tcl檔案,使用命令列命令:ns simple.tcl,在正常環境下會出現nam程式介面以及一個網路模擬拓撲圖。
方法/步驟2
第二步:網路規劃
節點數量:網路包含4個節點分別記為n0、n1、n2、n3。
鏈路數量:包含3條通訊鏈路n0到n2,n1到n2,n2到n3。
協議代理(Agent):Agent/UDP, Agent/TCP
資料來源:恆定速率發生器(CBR)
方法/步驟3
第三步:建立模擬指令碼檔案ex1.tcl
tcl指令碼檔案可以通過gedit進行編輯。
方法/步驟4
第四步:建立模擬器,定義網路原件,網路執行過程的追蹤檔案
set ns [new Simulator]
$ns color 0 blue
$ns color 1 red
$ns color 2 white
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set f [open out.tr w]
$ns trace-all $f
set nf [open out.nam w]
$ns namtrace-all $nf
$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-up
$ns duplex-link-op $n1 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n2 $n3 queuePos 0.5
方法/步驟5
第五步:建立udp協議代理,cbr資料發生器,將二者繫結,並在1.1 和1.2秒啟動兩個資料發生器
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
set udp1 [new Agent/UDP]
$ns attach-agent $n3 $udp1
$udp1 set class_ 1
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n3 $null0
set null1 [new Agent/Null]
$ns attach-agent $n1 $null1
$ns connect $udp0 $null0
$ns connect $udp1 $null1
$ns at 1.0 "$cbr0 start"
$ns at 1.1 "$cbr1 start"
set tcp [new Agent/TCP]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns attach-agent $n0 $tcp
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 1.2 "$ftp start"
$ns at 1.35 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"
puts [$cbr0 set packetSize_]
puts [$cbr0 set interval_]
方法/步驟6
第六步:定義模擬結束過程,在該過程中關閉兩個記錄檔案。最後,使用run命令啟動模擬。
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
puts "running nam..."
exec nam out.nam &
exit 0
}
$ns run
注意事項
NS2網路模擬具有一定的門檻,但本質上是用tcl、Otcl呼叫網路模擬庫函式的過程。用心學習相關教程後,熟練掌握加以應用就能成為自己的論文或者工程的有力研究工具。