Reputation: 347
The problem that I have is somehow very specific.
I have to implement a sliding window protocol in C over a link. My sender.c file recieves as parameters the speed, delay, and percentage of lost or corrupt files. The data is sent over a link. Since this is a school assignment I do not know the implementation details of the link but, sice the sender and receiver are required to init the link with a port and an ip I guess they are using sockets. Anyway, I'm trying to send to the reciever the connexion parameters in order to use them for timeouts and control flow. I create the data frame payload that sends the 2 ints representing the speed and delay using:
int s = (int)(*speed - '0');
int d = (int)(*delay - '0');
sprintf(t.payload,"%d%d",s,d);
When I print the s and d variables in the sender file the result is 1,1 which is correct. afterwards i'm sending the resulted payloar to the reciever, where payload[0] is assigned to another int variable called speed and payload[1] is assigned to another int called delay. the problem is that here they have the value 49 and not one as they should. I tried using the atoi() functio on them but when I do, the delay is converted successfully to 1 while the speed is converted to 11, which makes no sense. I've tried a lot of different ways to make it work, sending them as chars and converting them at the receiving end did not help either.
Any ideas?
PS: sorry for the gigantic post and my english mistakes!
Upvotes: 0
Views: 865
Reputation: 121427
I assume 't' is struct variable and payload is a character array. You are sending two numbers as char array. Its not possible to convert them back to integers from a char* without some sort of trickery. For example, if your payload is "12345", then how to extract two correct numbers that you sent from the otherside? All you know is "12345" is a concatenation of 2 numbers. It could be (1,2345) or (12,345) or (1234, 5).... etc.
I would suggest you to run the send command twice and receive accordingly. Like:
char str[10]; //a temporary variable
sprint(str,"%d", speed);
send (.......); //receive just delay alone on the other side
sprint(str,"%d", delay);
send(........);
An alternative could be insert a character as identifier and tokenize (strtok) when extracting numbers. Like:
sprint(t.payload, "%dZ%d",speed, delay); //sender side
/* Here 'Z' is used as a delimiter */
On the receiver side:
char *tok, *str;
receive(str, ....);
tok=strtok(str,"Z");
speed = atoi(tok);
tok=strtok(NULL);
delay=atoi(tok);
If you are sending more than 2 numbers, you are take care of strtok and insertion of 'Z' accordingly.
Upvotes: 1