[toc]
TCP/UDP 区别,使用场景
- TCP 是面向连接、可靠的流协议。
- UDP 是不具有可靠性的数据报协议。应用有时候会根据自己的需要进行重发处理。
如何识别通信
通过五个属性来识别一个通信:
- 源 IP
- 目的 IP
- 源端口
- 目的端口
- 协议号(包含在 IP 首部中)
数据到达 IP 层后,根据 IP 首部中的协议号分发给不同的运输层模块(TCP 和 UDP 模块),由相应模块对端口号进行处理。
对于知名端口号,TCP 和 UDP 模块中对应的应用层服务都是一致的,因此和协议无关,例如 53 号端口用于 DNS 服务,80 端口用于 HTTP。
使用场景
TCP 用于在传输层有必要实现可靠传输的情况。
UDP 主要用于那些对高速传输和实时性有较高要求的通信或广播通信。RIP、DHCP 等基于广播的协议要依赖 UDP。
UDP
- 不提供控制机制
- 提供面向无连接的通信服务
- 不提供可靠传输
- 不会延迟发送应用层交付的数据,也不会进行分包处理,将应用层交付的数据立刻原样发送到网络,因此适合即时通信
- 无拥塞控制机制
- 不重传、无前向纠正
需要以上细节控制时,需要在应用层实现控制机制。
UDP 的特点在于:
- 无连接,随时发送数据
- UDP 报文长度短,处理简单高效
- 支持多播广播
利用以上特点,在以下场景中经常使用 UDP:
- 数据包较少的通信(DNS、SNMP)
- 视频、音频、游戏等多媒体通信(即时通信)
- 广播通信(广播、多播)
TCP
- 提供可靠传输
- 面向连接
- 与 UDP 不同,对数据传输进行控制,任务划分不同
如何实现可靠传输
实现可靠传输需要考虑的问题:
- 数据损坏
- 数据重复
- 数据丢失
- 数据乱序
TCP 实现可靠传输的策略:
- 检验和,检测数据完整性和正确性
- 序列号,与重传机制、确认应答一起解决数据乱序、重复和丢失问题
- 确认应答
- 重发控制
- 连接控制
- 窗口控制,引入滑动窗口,以解决对每个 TCP 报文进行确认带来的性能损耗。也就是说,如果没有滑动窗口,发送方每次发送一个 TCP 包就要等待对这个包的确认,才能发送下一个包,这样浪费了信道利用率。引入滑动窗口后,发送方可以连续发送窗口内的数据,而不用等待每个包的确认报文。
滑动窗口
窗口大小就是无需等待确认应答而可以继续发送的数据的最大长度。
发送方如果连续收到三个对同一个 seq 进行确认的 ACK,就会重发相应的数据。
同时,TCP 的流量控制也是利用窗口大小实现,为了解决在发送方数据发送过快,接收端处理能力有限,将数据丢弃导致的发送方重传,带来的网络资源浪费。
为了避免接收方窗口大小为 0 时,发送方无法发送,接受方窗口大小恢复后发送窗口更新通知,而该报文丢失,接收方等待数据而造成的死等局面,加入了窗口探测报文,发送方在超过超时重传时间后发送窗口探测报文。
TCP 拥塞控制
在网络拥塞时,一个新的连接如果突然发送大量数据,可能会造成网络瘫痪。
因此,TCP 在通信开始时采用慢启动算法,限制发送数据量。在连接建立之后,将拥塞窗口大小设置为 1 个 MSS,接着每一个已发送报文被确认都使拥塞窗口大小增加一个 MSS,这样会导致拥塞窗口大小指数级增加,为了防止拥堵状况激增,设置慢开始门限,在拥塞窗口大小达到慢开始门限时,采用拥塞避免算法,以 1 个 MSS 为步长线性增加拥塞窗口大小。
以上没有考虑重传机制被触发的情况。
重传机制在两种情况下被触发:超过重传时间、连续收到三个同样的 ACK。
- 超过重传时间时,设置慢开始门限为当前窗口大小的一半,并重置拥塞窗口大小为 1 个 MSS,重新开始慢开始算法。
- 连续收到三个 ACK 时,说明当前网络拥塞状况并不严重,且发生了丢包,此时需要使用快重传算法,立即重传丢失的包,并且启动快恢复算法,把慢开始门限调整为当前拥塞窗口大小的一半,把拥塞窗口大小设置为慢开始门限大小加 3 MSS,直接开始拥塞避免算法。
OSI 七层模型
OSI 参考模型,将通信协议中必要的功能分成了 7 层。
- 每个分层接收下一层提供的特定服务
- 负责为上一层提供特定服务
- 上下层之间进行交互是所遵循的约定叫做“接口”
- 同一层之间的交互所遵循的约定叫做“协议”
分层的优势与劣势:
- 优势:扩展性和灵活性较强,系统中某些分层发生变化,也不会波及整个系统
- 劣势:过分模块化
OSI 参考模型
应用层
针对特定应用的协议,如 SMTP、TELNET、FTP 协议,都是针对特定应用而制定的应用层协议。
表示层
将应用处理的信息与网络传输格式相互转换。主要负责数据格式的转换。
会话层
负责建立和断开通信连接,以及数据的分割等数据传输相关的管理。
传输层
起着可靠传输的作用,只在通信双方节点上进行处理,而无需在路由器上进行处理。
网络层
将数据传输到目标地址。这一层主要负责寻址和路由选择。
数据链路层
负责物理层面上互联的、节点之间的通信传输。
将 0-1 序列划分为具有意义的数据帧传送给对端。
物理层
负责 0、1 比特流与电压高低、光的闪灭之间的转换(0、1编码对应的物理含义)。
网络的构成要素
设备 | 作用 |
---|---|
网卡 | 使计算机联网的设备 |
中继器 | 从物理层延长网络的设备 |
网桥/2层交换机 | 从数据链路层延长网络的设备 |
路由器/3层交换机 | 通过网络层转发分组数据的设备 |
4-7层交换机 | 处理传输层以上各层 网络传输的设备 |
网关 (gateway) | 转换协议的设备 |
面试中提到的路由器和交换机分别工作在哪层中的交换机,原理上等同于多端口网桥,而网桥的作用是在数据链路层上连接两个网络。
根据 MAC 地址转发数据帧,路由器根据 IP 地址转发分组报文。