我正在開發一個計算機網絡項目來模擬TCp/IP模型,我有一個很奇怪的問題。這很簡單,但我無法弄清楚我的代碼有什麼問題。在我的傳輸函數下面,我有一個while循環,它將單獨的幀收集到一個緩衝區中,每當我去收集一個新幀時清空緩衝區。問題在於while循環從下一幀收集1個額外的變量到前一幀。任何幫助將不勝感激!while循環不正確地重複
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
這裏是輸出我得到:
FRAME:STX102000000000127.0.0.1000000000000000abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd1eb5ETX
FRAME:STX101010000000127.0.0.1000000000000000efghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghi1f1bETXSTX
FRAME:101020000000127.0.0.1000000000000000jklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn1f35ETXSTX0
FRAME:85031000000127.0.0.1000000000000000opqrstuvwxyzabcdefghijklmnopqrstuvwxyzab 184aETX
第一幀是好的。第二幀不應該在最後有一個STX。第三幀不應該有STX和0結尾。第四框架應該對前方的STX和0:/
'sizeof(char)'是'1'。 –
我相信'while(k> = 0)'應該是'while(k> 0)',否則你會做一次額外的迭代。 –
是的,我認爲它可能是,但它沒有任何影響,當我改變它「while(k> 0);」 –