Post

NS2网络模拟器的使用

NS2网络模拟器的使用

Network Simulator,是一种面对对象的网络仿真器

介绍

采用c++和Otcl两种语言进行开发。 网络组件模拟网络设备或节点的通信,他们通过指定仿真场景和仿真进程,交换特定的分组来模拟真实网络情况,并将执行情况记录到日志文件(Trace文件)

安装

方法一

由于NS2在Ubuntu的软件源已经有了,所以直接用apt-get下载

1
sudo apt-get install ns2

此方法虽然能运行ns2,但是后续运行nam却打不开gui

方法二

1
curl -O http://nchc.dl.sourceforge.net/project/nsnam/allinone/ns-allinone-2.35/ns-allinone-2.35.tar.gz

下载ns2.35版的压缩包,然后解压。当然,直接使用curl下载压缩包可能会很慢,所以这里还是推荐使用迅雷下载,然后再通过共享文件夹传到虚拟机

参考Installation of NS2 in Ubuntu 22.04 | NS2 Tutorial 2 (nsnam.com)

1
2
3
4
5
6
7
8
# PATH
export PATH=$PATH:/home/lyp/MANET/ns-allinone-2.35/bin:/home/lyp/MANET/ns-allinone-2.35/tcl8.5.10/unix:/home/lyp/MANET/ns-allinone-2.35/tk8.5.10/unix

# LD_LIBRARY_PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/lyp/MANET/ns-allinone-2.35/otcl-1.14:/home/lyp/MANET/ns-allinone-2.35/lib

# TCL_LIBRARY
export TCL_LIBRARY=$TCL_LIBRARY:/home/lyp/MANET/ns-allinone-2.35/tcl8.5.10/library

输入ns测试是否安装成功

1
2
3
% puts "hello world"
hello world
% exit

编写tcl脚本

  • 创建模拟器对象,用来定义和控制模拟过程
  • 设置跟踪文件
  • 创建网络拓扑结构
  • 设置代理和应用层协议,并进行绑定
  • 使用模拟器对象的at过程设置节点时间和时间的对应关系
  • 使用模拟器对象的run过程开始模拟
  • 结果分析(模拟过程数据保存在trace文件中)
    • 对trace文件进行数据分析
    • 同时使用gnuplot显示数据分析结果

Tcl

Tcl只支持“字符串”一种数据结构,分割符就是空格

命令

1
2
command arg1 arg2 ...
puts "Hello world"

变量

1
2
3
4
set x 100   # 令x=100
unset x     # 删除变量x

使用info命令查看变量是否存在

替换

  • []:执行命令,获取结果
    • [expr ...]用于执行数学表达式或进行算术计算
    • [exec ls]用于执行ls指令
    • ….
1
puts [expr 1 + 6 + 9]
  • $x:变量替换,获取变量值
1
2
set x 10
puts $x
  • \:转义字符
  • ""
1
puts "hello\n world"

流程控制

  • ifelse
1
2
3
4
5
6
7
8
9
set num 5

if {$num > 10} {
    puts "num大于10"
} elseif {$num == 10} {
    puts "num等于10"
} else {
    puts "num小于10"
}
  • switch
1
2
3
4
5
6
7
8
9
10
11
switch $char {
	A {
		puts "hello A"
	}
	B {
		puts "hello B"
	}
	default {
		puts "invalid"
	}
}

循环

1
2
3
4
5
6
7
8
9
10
11
12
13
while {condition} {
	statement
}

for {init} {condition} {increment} {
	statement
}

for {set a 10} {$a < 20} {incr a} {
	puts "value of a: $a"
}

# 同样有break和continue

过程

1
2
3
4
5
6
7
8
9
10
11
proc procedureName {args} {
	body
}

proc helloworld {} {
	puts "Hello world"
}

proc add {a, b} {
	return [expr $a + $b]
}

OTcl

面对对象的Tcl,是Tcl的一个模块。允许在Tcl中定义类和对象,以及使用面向对象编程的概念,如封装、继承和多态。

simulator类

每个模拟过程需要一个类整个过程进行控制和管理。这个类封装了节点(note),链路(link),代理(agent),数据分组格式等

  • 整个模拟过程通过创建一个模拟类对象开始,通过调用这个对象的各个过程实现创建节点,构建拓扑结构图,对模拟的各个方面进行配置,定义事件,根据定义的事件模拟整个网络的运行等
1
set ns [new Simulator]
1
2
3
4
5
6
7
8
set ns [new Simulator]

proc handle_fun {} {
    puts "this is event handle function"
}

$ns at 5.0 "handle_fun"  # 仿真时间5.0秒时执行一个事件处理函数
$ns run    # 网络模拟器开始运行

节点note

交换机、路由器等网络设备在NS2中统统抽象为一个节点

This post is licensed under CC BY 4.0 by the author.