emen
emen

Reputation: 6318

Sending and receive two strings in C Socket

This is the client side where it prompts user to enter a string and send it to the server

//send
printf("\nPlaintext : ");
gets(send_data);
send(sock,send_data,strlen(send_data), 0);

//recv
bytes_recieved = recv(sock, recv_data, 1024, 0);
recv_data[bytes_recieved] = '\0';
printf("\nEnciphered text = %s " , recv_data);
fflush(stdout);
close(sock);

And this is the server side.

sin_size = sizeof(struct sockaddr_in);

//accept
connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);

printf("\n I got a connection from (%s , %d)", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

//recv
bytes_recieved = recv(connected, recv_data, 1024,0);

recv_data[bytes_recieved] = '\0';

printf("\n RECIEVED DATA = %s " , recv_data);

cod = encipher(recv_data, key, 1); //printf("Code: %s\n", cod);
dec = encipher(cod, key, 0); //printf("Back: %s\n", dec);

//send
send(connected, cod, strlen(cod), 0);
send(connected, dec, strlen(dec), 0);

So the thing is, I want to send two strings named 'plaintext' and 'key' from the client. At the server side, I expected it to receive the two strings and process it under encipher() function and then send it back to the client.

How do I send two strings from a client and receive two strings from the server?

Upvotes: 2

Views: 4649

Answers (2)

Rocky Pulley
Rocky Pulley

Reputation: 23301

send a 16bit short containing the size of the 1st string, then the 1st string, then another short containing the size of the 2nd string then the 2nd string. On the server, read a 16bit int then read that many bytes, then do the same for the 2nd string.

Upvotes: 0

mathematician1975
mathematician1975

Reputation: 21351

I would send the string first then get the server to write back some confirmation to the client that it received it. Then the client can send the key, the server can do what it needs to and return the message to the client. If you keep the socket connection open you can continue to send and receive information from/to either end of the connection with send() and recv(). There are a number of ways depending on the structure of your strings. You could use a delimiter in the data you send to the server to indicate the end of the string, so that the portion that remains is your key - this would allow the server to receive the data in one packet and reply in one packet. I am not sure there is a right way to do it - you must decide based on the needs of your application. Either way, you should check the return values of the socket functions to check that you are getting and sending what you think you are.

Upvotes: 1

Related Questions