S5 传输层:UDP协议
一、举例
二、端口号
有0~65535的编号:
- 编号0~1023为系统端口号,它们被指派给了 TCP/IP 最重要的一些应用程序
- 编号1024~49151为登记端口号,为没有系统端口号的应用程序使用
- 编号49152~65535为短暂端口号,是留给客户进程选择暂时使用的
三、UDP特性
无连接,尽最大努力交付(不可靠),面向报文,没有拥塞控制,支持一对一、一对多、多对一和多对多
S5作业 尝试抓取一个UDP数据报,并解读其内容
STEP 01
首先需要一个小程序,用于向指定IP地址的指定端口发送一个指定内容的UDP数据报。
使用github把它下载下来,并编译:
cd Desktop
git clone https://github.com/shiyanlou/tcp_ip_5
cd tcp_ip_5
gcc -o test test.c
这个 C 程序会向 IP 地址 192.168.1.1 的 7777 端口 发送一条 "hello" 消息
STEP 02
依次输入以下命令安装,并运行tcpdump:
sudo apt-get update
sudo apt-get install tcpdump
sudo tcpdump -vvv -X udp port 7777
STEP 03
最小化当前终端,另开启一个终端,输入以下命令运行刚才编译好的C程序test:
STEP 04
test程序运行结束,返回刚才运行 tcpdump 的终端查看抓包结果:
STEP 05
解析
STEP 06
修改 C 程序,向不同的 IP,不同的端口发送不同的内容:
STEP 07
重新编译运行
STEP 08
解析
STEP 09
test.c源码
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string.h>
int main(void)
{
int sockfd;
struct sockaddr_in server;
char msg[20] = {0};
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd < 0) {
perror("socket error!\n");
exit(-1);
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("192.168.1.1");
server.sin_port = htons(7777);
strncpy(msg, "hello", sizeof("hello"));
printf("send message: %s\n", msg);
if(sendto(sockfd, msg, 20, 0, (struct sockaddr *)&server, sizeof(server)) != 20) {
perror("socket error!\n");
exit(-1);
}
exit(0);
}