Return-Path: william@bourbon.usc.edu Delivery-Date: Fri Oct 17 06:16:22 2008 X-Spam-Checker-Version: SpamAssassin 3.2.3 (2007-08-08) on merlot.usc.edu X-Spam-Level: X-Spam-Status: No, score=-2.3 required=5.0 tests=AWL,BAYES_00 autolearn=ham version=3.2.3 Received: from bourbon.usc.edu (bourbon.usc.edu [128.125.9.75]) by merlot.usc.edu (8.14.1/8.14.1) with ESMTP id m9HDGMFq029719 for ; Fri, 17 Oct 2008 06:16:22 -0700 Received: from bourbon.usc.edu (localhost.localdomain [127.0.0.1]) by bourbon.usc.edu (8.14.2/8.14.1) with ESMTP id m9HDOmHK014200 for ; Fri, 17 Oct 2008 06:24:48 -0700 Message-Id: <200810171324.m9HDOmHK014200@bourbon.usc.edu> To: cs551@merlot.usc.edu Subject: Re: Regarding strlen/numbytes Date: Fri, 17 Oct 2008 06:24:48 -0700 From: Bill Cheng Someone wrote: > We are having an error with the string length of UOID printed out. > > For example: > > The first receive for the 27 bytes header is: > > if ((bnumbytes=recv(sockfd, &brecvBuf[0],27,0)) == -1) > { > perror("recv"); > } > > Then we do a memcpy for parsing header fields as follows: > > memcpy(&brecvmsgType,&brecvBuf[0],1); // Get the message > type > memcpy(&brecvUOID[0],&brecvBuf[1],20); // Get the UOID > cout<<"************uoid3 = "< This prints out UOID Length = 20 > > memcpy(&brecvTTL,&brecvBuf[21],1); // Get the TTL > cout<<"************uoid3 = > "< > memcpy(&bresField,&brecvBuf[22],1); // Get the reserved field > cout<<"************uoid3 = > "< > memcpy(&brecvmsgLength,&brecvBuf[23],4); // Get > the msglength > cout<<"************uoid3 = "< // THIS ALSO PRINTS OUT 21 > > If we print out the actual UOID received , the 20 byte UOID is same as was > sent by the sender. > > But the length of the UOID keeps changing due to some reason, and this > changes the total number of bytes sent henceforth, that results in an error > in all subsequent send/receives. > > All we are doing is a memcpy like warmup#1 , are we printing the string > length incorrectly ? UOID is the output of the SHA1() function. It's always 20 bytes long and it's *binary*, which means that it can contain 0x00. strlen() is a function that will return the length of a *null-terminated string*. As soon as it sees a 0x00, it returns the length of *what it thinks is a string*. Therefore, strlen() *cannot* be used with binary data. You also need to print binary data differently. You can use: for (i=0; i < 20; i++) { printf("%02x", (unsigned char)buf[i]); } -- Bill Cheng // bill.cheng@usc.edu