1

我正在开发一个网络软件作为大学考试的一部分。软件快完成了,但实际上我正在完成并发部分(使用 fork())。我的需要是在客户端和服务器之间交换这两条消息作为握手。这里是一个例子: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,但他告诉我他收到的是 19476 而不是 3506,这不是真的。我还注意到,如果我尝试发送数字消息而不将它们转换为网络字节顺序,情况会变得更糟。很多天我都在与这个作斗争,我不知道该怎么想了。

4

1 回答 1

1

当您从客户端发送 PING 时,客户端 ntohs 在转换为 ascii 之前无法在整数端口上执行 a ,但是在服务器上接收时您执行 a ntohs ,我认为这是导致错误的原因。 在客户端 PING 端的这些行上做一些事情可能会有所帮助,但是如果服务器和客户端的字节序不同,这仍然容易出错。

char *itoaPortBuffer;
itoaPortBuffer = malloc(6*sizeof(char));
itoa(ntohs(childLocalPort[0]), itoaPortBuffer, 10);
strcat(pingProcedureString, itoaPortBuffer);
strcat(pingProcedureString, ":DOWNLOAD");
于 2012-03-26T14:02:41.490 回答