2012-03-26 56 views
1

提取号码我正在开发的网络软件作为大学考试的一部分。该软件几乎完成,但实际上我正在完成并发部分(使用fork())。 我的需求是在客户端和服务器之间交换这两条消息作为握手。 下面一个例子: PING:3506:下载 PONG:5605ÇUDP网络,从数据报消息

这里我的方式来处理这些消息: 在客户端,那是谁发送ping主机:3506:下载,我写

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部分缺失,因为我想集中在第一个非工作PA RT。服务器正确接收(正如我可以从Wireshark看到的)消息PING:3506:DOWNLOAD,但他告诉我他收到了19476而不是3506,这是不正确的。 我还注意到,如果我尝试发送数字信息而不将它们转换为网络字节顺序,情况会变得更糟。我很多天都在为此而战,而且我不知道该怎么想。

+0

1)你的缓冲区太小。 2)不需要使用malloc()分配它们,您可以轻松地在堆栈上分配几百字节大小的缓冲区。 3)你认为网络数据包是nul-terminated。他们不是。 4)哎呀,我忽略了'buff [n] = 0; '... – wildplasser 2012-03-26 13:45:57

回答

1

当您从客户端发送PING时,客户端在转换为ascii之前无法在整数端口上执行ntohs,但在服务器上接收到请求时,我执行ntohs,我认为这是导致错误的原因。这样做对客户端PING这些方针的东西可能有助于然而,这仍然是容易出错,如果服务器和客户端的字节顺序不同。

char *itoaPortBuffer; 
itoaPortBuffer = malloc(6*sizeof(char)); 
itoa(ntohs(childLocalPort[0]), itoaPortBuffer, 10); 
strcat(pingProcedureString, itoaPortBuffer); 
strcat(pingProcedureString, ":DOWNLOAD");