I am facing multiple problem creating a small ftp like client / server (tcp)
the client have a prompt.
the How to stop receiving issue. Sending data throught my socket from my client to server or vise-versa.
For example, from the server sending some string to the client. How the client know when to stop reading the socket and leave the recv()
loop to print back the prompt
That why i created transfert functions
to know when to stop by pre-send if it's the last send or not (CONT - DONE
) and it work great. (code below)
Then i needed to execute command like ls
on the server and send the result to the client, so i thought 2 options.
- dup
execv()
in achar*
and use my transfert functions. - dup
execv()
output directly in my socket.
The second options is cleaner, but it's make me facing the first issue about how to stop the recv()
loop.
bonus question: how to dup execv()
to a string. i thought using mmap
thanks to the fd
parameter, but i still need to know the size in advance.
# define BUFFSIZE 512
# define DONE "DONE"
# define CONT "CONT"
int send_to_socket(int sock, char *msg)
{
size_t len;
int ret[2];
char buff[BUFFSIZE+1];
len = strlen(msg);
bzero(buff, BUFFSIZE+1);
strncpy(buff, msg, (len <= BUFFSIZE) ? len : BUFFSIZE);
/*strncpy(buff, msg, BUFFSIZE);*/
ret[0] = send(sock, (len <= BUFFSIZE) ? DONE : CONT, 4, 0);
ret[1] = send(sock, buff, BUFFSIZE, 0);
if (ret[0] <= 0 || ret[1] <= 0)
{
perror("send_to_socket");
return (-1);
}
// recursive call
if (len > BUFFSIZE)
return (send_to_socket(sock, msg + BUFFSIZE));
return (1);
}
char *recv_from_socket(int cs)
{
char state[5];
char buff[BUFFSIZE+1];
char *msg;
int ret[2];
msg = NULL;
while (42)
{
bzero(state, 5);
bzero(buff, BUFFSIZE+1);
ret[0] = recv(cs, state, 4, 0);
ret[1] = recv(cs, buff, BUFFSIZE, 0);
if (ret[0] <= 0 || ret[1] <= 0)
{
perror("recv_from_socket");
return (NULL);
}
// strfljoin(); concat the strings and free the left parameter
msg = (msg) ? strfljoin(msg, buff) : strdup(buff);
if (strnequ(state, DONE, 4))
break ;
}
return (msg);
}