私は大学の試験の一環としてネットワークソフトウェアを開発しています。ソフトウェアはほぼ完成していますが、実際には並行部分を完成させています(fork()を使用)。私のニーズは、クライアントとサーバーの間でこれら2つのメッセージをハンドシェイクとして交換することです。ここに例があります:PING:3506:DOWNLOAD PONG:5605
これらのメッセージを処理する私の方法は次のとおりです。クライアント側では、PING:3506:DOWNLOADを送信するホストです。
int *childLocalPort;
childLocalPort = malloc(sizeof(int));
childLocalPort[0] = (SERV_PORT_OFFSET + getPort(&portArray, &pidArray, &arrayCounter, cpid));
char *pingProcedureString;
pingProcedureString = malloc(30*sizeof(char));
strcpy(pingProcedureString, "PING:");
char *itoaPortBuffer;
itoaPortBuffer = malloc(6*sizeof(char));
itoa((childLocalPort[0]), itoaPortBuffer, 10);
strcat(pingProcedureString, itoaPortBuffer);
strcat(pingProcedureString, ":DOWNLOAD");
if (sendto(sockfd, pingProcedureString, strlen(pingProcedureString), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("errore in sendto1");
exit(1);
}
free(itoaPortBuffer);
free(pingProcedureString);
n = recvfrom(sockfd, buff, MAXLINE, 0, NULL, NULL);
buff[n] = 0;
if(strcmp(buff,"PONG"))
{
int *childRemotePort;
childRemotePort = malloc(sizeof(int));
strtok(buff, ":");
childRemotePort[0] = ntohs(strtok(NULL, ":"));
printf("Remote port is %d\n", childRemotePort[0]);
close(pipeLocalPort[0]); /* Close unused read end */
write(pipeLocalPort[1], childLocalPort, sizeof(int)
close(pipeLocalPort[1]); /* Reader will see EOF */
close(pipeRemotePort[0]);
write(pipeRemotePort[1], childRemotePort, sizeof(int));
close(pipeRemotePort[1]);
}
サーバー側では、PONG:5605を送信するホストです。
if ((n > 0) && strcmp(recvline,"PING"))
{
int *childRemotePort;
childRemotePort = malloc(sizeof(int));
strtok(recvline, ":");
char *buffTemp;
buffTemp = calloc(5, sizeof(char));
strcpy(buffTemp,strtok(NULL, ":"));
childRemotePort[0] = ntohs(atoi(buffTemp));
strtok(recvline, ":");
printf("Remote child client port is: %d\n", childRemotePort[0]);
}
お気づきのように、最初の非動作部分に焦点を当てたいので、PONG部分が欠落しています。サーバーは(Wiresharkからわかるように)メッセージPING:3506:DOWNLOADを正しく受信しますが、3506ではなく19476を受信したと言っており、これは正しくありません。また、数値メッセージをネットワークバイトオーダーに変換せずに送信しようとすると、状況が悪化することにも気づきました。私は何日もこれと戦っています、そして私はもう何を考えるべきかわかりません。