为了成为自由自在的人而奋斗!
分类: C/C++
2011-05-19 14:27:03
#include
#include
typedef struct hmw_ip_header_s {
unsigned ver : 4;
unsigned header_len : 4;
unsigned char differ_service;
unsigned short int total_len;
unsigned int flag;
unsigned fflag : 3;
unsigned offset : 13;
char ttl;
char protcol;
short int check_sum;
unsigned long src_ip;
unsigned long dest_ip;
}hmw_ip_header_t;
typedef struct packet_s {
char str[256];
short int check_sum;
}packet_t;
/**
* hmw_anti_code_sum - 反码算术运算求和 Anti-code operator sum
*
* @str:检验内容
* @len:检验长度
*
* 即16位分别相加,然后把值取反 放入校验部分,len最好为2自己的倍数
*/
short int hmw_anti_code_sum(void *str, int len)
{
int i;
short int *op1, ret;
unsigned char *tmp_str;
int real_len;
printf("len = %d line %d\n", len, __LINE__);
/* 把字符串弄成2字节的倍数的形式 */
real_len = (len + 1) & ((~0ul) << 1);
printf("real_len = %d\n", real_len);
tmp_str = (unsigned char *)malloc(real_len);
if (tmp_str == NULL) {
printf("malloc failed!\n");
return 0;
}
memset(tmp_str, 0, real_len);
memcpy(tmp_str, str, len);
ret = 0;
for (i = 0; i < real_len; i += 2) {
op1 = (short int *)(tmp_str + i);
ret += *op1;
}
free(tmp_str);
ret = ~ret;
printf("ret is %d\n", ret);
return ret;
}
int main(void)
{
packet_t test;
int ret;
memset(&test, 0, sizeof(test));
printf("please input something!\n");
scanf("%s", test.str);
printf("str is %s\n", test.str);
ret = hmw_anti_code_sum((unsigned char *)(&test), sizeof(test));
test.check_sum = ret;
if (hmw_anti_code_sum((unsigned char *)(&test), sizeof(test)) == 0) {
printf("check ok!\n");
} else {
printf("check failed!\n");
}
return 0;
}