中等模拟 | 北邮OJ | 98. IP数据包解析

版权声明:本文纯属作者口胡,欢迎转载 https://blog.csdn.net/TQCAI666/article/details/86674096

https://vpn.bupt.edu.cn/http/10.105.242.80/problem/p/98/

  • IP头部
    在这里插入图片描述

  • TCP头部
    在这里插入图片描述

数据解析

45 00 00 34 //0034表示总长度, 即52B, 5表示首部长度, 5*4B
7a 67 40 00
40 06 63 5a 
0a cd 0a f4 //源地址 10.205.10.244
7d 38 ca 09 //目的地址 125.56.202.9

cd f6 00 50 //源端口, 目的端口
b4 d7 ae 1c
9b cf f2 40
80 10 ff 3d
fd d0 00 00

Case #1
Total length = 52 bytes
Source = 10.205.10.244
Destination = 125.56.202.9
Source Port = 52726
Destination Port = 80

AC代码

有点意思, 码量较大
需要训练做模拟题的速度

#include <bits/stdc++.h>
#define FF(a,b) for(int a=0;a<b;a++)
#define F(a,b) for(int a=1;a<=b;a++)
#define LEN 100
#define INF 1000000
#define bug(x) cout<<#x<<"="<<x<<endl;

using namespace std;
typedef long long ll;

char buf[1000];
char str[100][10];

int hex2int(char ch){
    if(ch>='a'){
        return ch-'a'+10;
    }else{
        return ch-'0';
    }
}

int hex2int(char *ch){
    int n=strlen(ch);
    int ans=0;
    int base=1;
    for(int i=n-1,j=0
        ;i>=0;
        i--,j++)	//脑子秀逗了, 其实写个单循环就好了
    {
        ans+=hex2int(ch[i])*base;
        base*=16;
    }
    return ans;
}




int main()
{
//    freopen("./in","r",stdin);
    int N;
    scanf("%d",&N);
    FF(i,N){
        //gets(buf); 可以用gets读入带空格的一行
        int n=0;
        while(1){
            scanf("%s",str[n++]);
            char pd=getchar();
            if(pd=='\n' || pd==EOF)
                break;
        }
        int IPlen=hex2int(str[0][1]);
        strcat(str[2],str[3]);
        int TOTlen=hex2int(str[2]);
        printf("Case #%d\n",i+1);
        printf("Total length = %d bytes\n",TOTlen);
        printf("Source = %d.%d.%d.%d\n",hex2int(str[12]),hex2int(str[13]),hex2int(str[14]),hex2int(str[15]));
        printf("Destination = %d.%d.%d.%d\n",hex2int(str[16]),hex2int(str[17]),hex2int(str[18]),hex2int(str[19]));
        strcat(str[IPlen*4],str[IPlen*4+1]);
        strcat(str[IPlen*4+2],str[IPlen*4+3]);
        printf("Source Port = %d\n",hex2int(str[IPlen*4]));
        printf("Destination Port = %d\n",hex2int(str[IPlen*4+2]));
        puts("");

    }
    return 0;
}
//Case #1
//Total length = 52 bytes
//Source = 10.205.10.244
//Destination = 125.56.202.9
//Source Port = 52726
//Destination Port = 80

猜你喜欢

转载自blog.csdn.net/TQCAI666/article/details/86674096
今日推荐