简体   繁体   中英

Converting to integer from char buffer in sockets

Client Side:

char buf[1024];  
int packetAmt = fileSize/PACKETSIZE;
cout<<"Number of packet amounts: "<<packetAmt<<endl; 

// send packet amount to serv
ibytessent=send(s,itoa(packetAmt,buf,10),sizeof(buf),0);   

Server side:

char szbuffer[1024];
if((ibytesrecv = recv(s1,szbuffer,sizeof(szbuffer),0)) == SOCKET_ERROR)
     throw "Receive error in server program\n";
cout << "This is the number of packets sent: " << szbuffer << endl;
packetAmt=atoi(szbuffer);
cout << "This is the number of packets sent: " << packetAmt<< endl;

The integer returned after converting the char array into integer's doesn't match the string sent. However printing the string will return the correct value. I have also tried using the strtol function. Could the error occur when converting from integer to char array?

atoi will stop when it reaches the first non-numeric character. If you don't have a terminator in the receiver buffer, it might go past the intended end of the number. It also appears you didn't put a terminator in the sender's buffer either.

I realized the source of the problem, I had the following line of code which converted the sender's address information into hex values. All the following code had integer values interpreted as hex instead of decimal.

cout<<"accepted connection from "<<inet_ntoa(ca.ca_in.sin_addr)<<":"
<<hex<<htons(ca.ca_in.sin_port)<<endl;

Thank you for your input, it really helped narrow the problem down!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM