98. IP数据包解析 题目1475:IP数据包解析

// 题是不难,但是重要的是理解题意!先求IP头部长度

#include<stdio.h>

#include<string.h>
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("Case #%d\nTotal length = %d bytes\n", c++, sum2(str+6));  
            printf("Source = %d.%d.%d.%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;  
}  
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值