我正在研究一个计算机网络项目来模拟 TCp/IP 模型,但我遇到了一个非常奇怪的问题。这很简单,但我就是不知道我的代码有什么问题。在下面的传输函数中,我有一个 while 循环,它将单独的帧收集到一个缓冲区中,每次我去收集一个新帧时都会清除该缓冲区。问题是 while 循环正在从下一帧收集 1 个额外变量到前一帧。任何帮助将不胜感激!
void transmit(char *ipaddress){
char mode;
char *ap = calloc(MAX, sizeof(char)); //Arrays used to transfer data from each layer
char *Frame = calloc(MAX, sizeof(char));
mode = 's';
int i = 0, k = 0, j = 0;
ap = layer4(ap); //Each layer returns data that is stored
ap = layer3(ap, ipaddress);
ap = layer2(ap);
k = strlen(ap);
printf(" APLENGTH %d", k);
while(k >= 0){ //This is where I start collecting frames
memset(Frame,0,strlen(Frame));
while(ap[i] != 3 && ap[i+1] != 2){ //Stop if ETX followed by STX
Frame[i] = ap[j];
//printf("%d, Frame[%d]: %c",j,i,Frame[i]); This was for debugging.
i++; j++;
k--; //Decrement the amount of characters left in the total package
}
Frame[i] = ap[j]; //Append the last ETX bit to complete frame
// printf("\n");
//printf("%d, Frame[%d]: %c",j,i,Frame[i]);
i++,j++;
Frame[i] = '\0'; //Append terminate character
// printf("%d, Frame[%d]: %c",j,i,Frame[i]);
i = layer1(Frame, mode);
printf("FRAME: %s\n\n",Frame);
if(i != 0){
printf("Terminating Program");
exit(1); }
i = 0;
}
//ap = layer1(ap, mode);
} //Trasmit Layer
这是我得到的输出:
帧:STX102000000000127.0.0.1000000000000000abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd1eb5ETX
帧:STX101010000000127.0.0.1000000000000000efghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghi1f1bETXSTX
帧: 101020000000127.0.0.1000000000000000jklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn1f35ETXSTX0
帧: 85031000000127.0.0.1000000000000000opqrstuvwxyzabcdefghijklmnopqrstuvwxyzab 184aETX
第一帧很好。第二帧的末尾不应有 STX。第三帧的末尾不应有 STX 和 0。第四帧前面应该有一个 STX 和 0 :/