北邮复试机试:98:计算机网络IP

98:计算机网络IP

我们都学习过计算机网络,知道网络层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是目标端口号。

#include<iostream>
#include <cstdio>
#include <string>
//#include <algorithm>
#include <vector>
#include<cstring>
#include <iterator>
#include <algorithm>
#include<iostream>
using namespace std;

int num(char *c){               // 字符转换为数字
    if(*c>='0'&&*c<='9') return *c-'0';
    else return *c-'a'+10;   
}
int sum1(char *p){              // 求地址
    return 16*num(p)+num(p+1); 
} 
int sum2(char *p){             // 求端口
    return 256*16*num(p)+256*num(p+1)+16*num(p+3)+num(p+4); 
} 
int main(){ 
    int n, c = 1; 
    while(scanf("%d", &n)!=EOF){
        char str[1000];
        gets(str);                           
        while(n--){ 
            gets(str);                    //从缓冲区获取字符串 
            int IHL = num(str+1)*4*3;      //计算ip头部长度. 
            printf("THL %d\n",IHL);
            printf("Case #%d\nTotal length = %d bytes\n", c++, sum2(str+6)); 
            printf("sum2(str[6]) %d\n",sum2(str+6));
            printf("Source = %d.%d.%d.%d\n", sum1(str+36),sum1(str+39),sum1(str+42),sum1(str+45)); 
            printf("sum1(str[36])  %d,sum1(str[39])   %d,sum1(str[42])    %d,sum1(str[45]) %d\n",sum1(str+36),sum1(str+39),sum1(str+42),sum1(str+45));
            printf("Destination = %d.%d.%d.%d\n",sum1(str+48),sum1(str+51),sum1(str+54),sum1(str+57)); 
            printf("Source Port = %d\n",sum2(str+IHL)); 
            printf("Destination Port = %d\n\n",sum2(str+IHL+6)); 
        }
    } 
    return 0; 
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值