ppp协议编码与解码(2)
时间:2026-01-20
时间:2026-01-20
ppp协议编码与解码
解码实际上就是编码的逆运算,它除去转义字符,并对转义字符之后的字符的第6位去补码。 001 /* return: bytes decoded */
002 int pppDecode(unsigned char * buf, int len) {
003 unsigned char * pi, *po;
004 int i, olen;
005 unsigned char obuf[BUF_LEN];
006 if(len > BUF_LEN) {
007 return -1;
008 }
009 memset(obuf, 0, BUF_LEN);
010 pi = buf;
011 po = obuf;
012 olen = len;
013 for(i=0; i<len; i++) {
014 if(*pi == PPP_FRAME_ESC) {
015 /* skip the escape byte */
016 pi++;
017 olen--;
018 /* xor the 6th bit */
019 *po = *pi ^ PPP_FRAME_ENC;
020 }
021 else {
022 *po = *pi;
023 }
024 pi++;
025 po++;
026 }
027 memcpy(buf, obuf, olen);
028 return olen;
029 }
006~008: 检查要解码的字符长度。
014~020: 解码的主要实现,遇到转义字符,将其跳过,对紧接其后的字符的第6位去补码。
021~023: 其他字符,不做处理。
027~028: 修改缓冲区,返回解码后的字符长度。