1 #include <stdio.h> 2 #include <string.h> 3 4 // PPP数据帧每一帧都以标识字符0x7E开始和结束; 5 // 由于标识字符的值是0x7E,因此当该字符出现在信息字段中时,PPP需要对它进行转义。 6 // 当PPP使用异步传输时,它把转义字符定义为:0x7D,并使用字节填充RFC-1662标准。 7 // 字节填充RFC-1662标准规定如下: 8 // 1. 把信息字段中出现的每一个0x7E字符转变成字节序列(0x7D,0x5E) 9 // 2. 若信息字段中出现一个0x7D的字节(即出现了与转义字符相同的比特组合), 10 // 则把0x7D转义成两个字节序列(0x7D,0x5D) 11 // 3. 若信息字段中出现ASCII码的控制字符(即数值小于0x20的字符), 12 // 则在该字符前面加入一个0x7D字节,同时将该字符的编码加以改变 13 14 #define PPP_FRAME_FLAG ( 0x7E ) /* 标识字符 */ 15 #define PPP_FRAME_ESC ( 0x7D ) /* 转义字符 */ 16 #define PPP_FRAME_ENC ( 0x20 ) /* 编码字符 */ 17 18 int ppp_encode(unsigned char *in, int in_len, unsigned char *out, int *out_len) 19 { 20 unsigned char *pi, *po; 21 int i, tmp_len; 22 23 pi = in; 24 po = out; 25 tmp_len = in_len; 26 27 for(i = 0; i < in_len; i++) 28 { 29 if( *pi == PPP_FRAME_FLAG || *pi == PPP_FRAME_ESC || *pi < 0x20 ) 30 { 31 *po = PPP_FRAME_ESC; 32 po++; 33 tmp_len++; 34 *po = *pi ^ PPP_FRAME_ENC; 35 } 36 else 37 { 38 *po = *pi; 39 } 40 41 pi++; 42 po++; 43 } 44 *out_len = tmp_len; 45 46 return 0; 47 } 48 49 int ppp_decode(unsigned char *in, int in_len, unsigned char *out, int *out_len) 50 { 51 unsigned char *pi, *po; 52 int i, tmp_len; 53 54 pi = in; 55 po = out; 56 tmp_len = in_len; 57 58 for(i = 0; i < in_len; i++) 59 { 60 if(*pi == PPP_FRAME_ESC) 61 { 62 pi++; 63 tmp_len--; 64 *po = *pi ^ PPP_FRAME_ENC; 65 66 i++; 67 } 68 else 69 { 70 *po = *pi; 71 } 72 73 pi++; 74 po++; 75 } 76 *out_len = tmp_len; 77 78 return 0; 79 } 80 81 82 void printf_hex(char *title, unsigned char *hex, int n) 83 { 84 int i; 85 86 printf("%s", title); 87 for(i = 0; i < n; i++) 88 { 89 if(i % 16 == 0 && i != 0) 90 printf(" "); 91 printf("%02x ", (unsigned char )hex[i]); 92 } 93 printf(" "); 94 } 95 96 int main(void) 97 { 98 unsigned char p1[256]; 99 unsigned char p2[512]; 100 unsigned char p3[512]; 101 int i, len1, len2, len3; 102 103 len1 = sizeof(p1)/sizeof(p1[0]); 104 105 for(i = 0; i < len1; i++) 106 { 107 p1[i] = i % 256; 108 } 109 110 printf_hex("Before Encode:: ", p1, len1); 111 printf("Before Encode, len1: %d ", len1); 112 113 ppp_encode(p1, len1, p2, &len2); 114 115 printf_hex("After Encode:: ", p2, len2); 116 printf("After Encode, len2: %d ", len2); 117 118 ppp_decode(p2, len2, p3, &len3); 119 120 printf_hex("After Decode:: ", p3, len3); 121 printf("After Decode, len3: %d ", len3); 122 123 return 0; 124 }