题目描述
我们都学习过计算机网络,知道网络层IP协议数据包的头部格式如下:
其中IHL表示IP头的长度,单位是4字节;总长表示整个数据包的长度,单位是1字节。
传输层的TCP协议数据段的头部格式如下:
头部长度单位为4字节。
你的任务是,简要分析输入数据中的若干个TCP数据段的头部。 详细要求请见输入输出部分的说明。
输入格式
第一行为一个整数T,代表测试数据的组数。
以下有T行,每行都是一个TCP数据包的头部分,字节用16进制表示,以空格隔开。数据保证字节之间仅有一个空格,且行首行尾没有多余的空白字符。
保证输入数据都是合法的。
输出格式
对于每个TCP
数据包,输出如下信息:
Case #x
,x
是当前测试数据的序号,从1开始。
Total length = L bytes
,L
是整个IP数据包的长度,单位是1字节。
Source = xxx.xxx.xxx.xxx
,用点分十进制输出源IP地址。输入数据中不存在IPV6数据分组。
Destination = xxx.xxx.xxx.xxx
,用点分十进制输出源IP地址。输入数据中不存在IPV6数据分组。
Source Port = sp
,sp
是源端口号。
Destination Port = dp
,dp
是目标端口号。
对于每个TCP数据包,最后输出一个多余的空白行。
具体格式参见样例。
请注意,输出的信息中,所有的空格、大小写、点符号、换行均要与样例格式保持一致,并且不要在任何数字前输出多余的前导0,也不要输出任何不必要的空白字符。
2
45 00 00 34 7a 67 40 00 40 06 63 5a 0a cd 0a f4 7d 38 ca 09 cd f6 00 50 b4 d7 ae 1c 9b cf f2 40 80 10 ff 3d fd d0 00 00 01 01 08 0a 32 53 7d fb 5e 49 4e c8
45 00 00 c6 56 5a 40 00 34 06 e0 45 cb d0 2e 01 0a cd 0a f4 00 50 ce 61 e1 e9 b9 ee 47 c7 37 34 80 18 00 b5 81 8f 00 00 01 01 08 0a 88 24 fa c6 32 63 cd 8d
输出样例
Case #1
Total length = 52 bytes
Source = 10.205.10.244
Destination = 125.56.202.9
Source Port = 52726
Destination Port = 80
Case #2
Total length = 198 bytes
Source = 203.208.46.1
Destination = 10.205.10.244
Source Port = 80
Destination Port = 52833
#include<bits/stdc++.h>
using namespace std;
int tonum(string s){
int sum=0;
int num=0;
for(int i=0;i<s.size();i++){
if(s[i]>='0'&&s[i]<='9'){
num=s[i]-'0';
sum=sum*16+num;
}else if(s[i]>='a'&&s[i]<='f'){
num=s[i]-'a'+10;
sum=sum*16+num;
}
}
return sum;
}
int main(){
int T;
int IHL,total_len;
int src[4],des[4];
int srcp,desp;
string str,op;
cin>>T;
getchar();// 空行
for(int i=1;i<=T;i++){
getline(cin,str);
cout<<"Case #"<<i<<endl;
op=str.substr(6,5);
total_len=tonum(op);
printf("Total length = %d bytes\n",total_len);
op=str.substr(36,2);
src[0]=tonum(op);
op=str.substr(39,2);
src[1]=tonum(op);
op=str.substr(42,2);
src[2]=tonum(op);
op=str.substr(45,2);
src[3]=tonum(op);
printf("Source = %d.%d.%d.%d\n",src[0],src[1],src[2],src[3]);
op=str.substr(48,2);
des[0]=tonum(op);
op=str.substr(51,2);
des[1]=tonum(op);
op=str.substr(54,2);
des[2]=tonum(op);
op=str.substr(57,2);
des[3]=tonum(op);
printf("Destination = %d.%d.%d.%d\n",des[0],des[1],des[2],des[3]);
op=str.substr(60,5);
srcp=tonum(op);
printf("Source Port = %d\n",srcp);
op=str.substr(66,5);
desp=tonum(op);
printf("Destination Port = %d\n",desp);
if(i!=T){
printf("\n");
}
}
return 0;
}