In a multi-client/server implementation I am connecting the client and server and then taking inputs from the client's stdin to send to server (otherwise if there's an incoming message from the server, I am performing a recv() and I am using select() to switch between the two). Now, as an example, I am giving an input "LOGIN IP PORT" and that connects me to the server. And then I am back to the client's command line again.
NOW, when I am back at the command line again after the login command, if I press enter without typing any specific command, the previous LOGIN command is executed again, it seems. I think the stdin is not being flushed. Although I have done fseek(stdin,0,SEEK_END), it's still not getting flushed. The client side main loop code is as below:
while(TRUE) {
fd_max = server_fd;
FD_ZERO(&sock_list);
FD_SET(STDIN, &sock_list);
FD_SET(server_fd, &sock_list);
printf("\n[PA1-Client]$ ");
fflush(stdout);
fseek(stdin,0,SEEK_END);
selret = select(fd_max + 1, &sock_list, NULL, NULL, NULL);
if(selret < 0)
perror("Select failed");
else {
int sock_index;
for(sock_index = 0; sock_index<=fd_max; sock_index++) {
if(FD_ISSET(sock_index, &sock_list)) {
if(sock_index == STDIN) {
char* cmd = (char*) malloc(sizeof(char)*CMD_SIZE);
if(fgets(cmd, CMD_SIZE - 1, stdin) == NULL)
exit(-1);
cmd[strcspn(cmd, "\n")] = '\0'; char* token[3];
tokenize(cmd, token, " ");
if(!strcmp(token[0], "LOGIN")) {
server_fd = clientLogin(token[1], token[2]);
}
else if(!strcmp(token[0], "REFRESH")) {
clientRefresh(token[0]);
}
else if(!strcmp(token[0], "LOGOUT")) {
clientLogout(token[0]);
}
else if(!strcmp(token[0], "EXIT")) {
clientExit(token[0]);
exit(0);
}
else if(!strcmp(token[0], "SEND")) {
clientSend(cmd);
}
else if(!strcmp(token[0], "BROADCAST")) {
clientBroadcast(cmd);
}
else if(!strcmp(token[0], "BLOCK")) {
clientBlock(cmd);
}
else if(!strcmp(token[0], "UNBLOCK")) {
clientUnblock(cmd);
}
else if(!strcmp(token[0], "AUTHOR")) {
commonAuthor();
}
else if(!strcmp(token[0], "IP")) {
commonIP();
}
else if(!strcmp(token[0], "PORT")) {
commonPort();
}
else if(!strcmp(token[0], "LIST")) {
commonList();
}
}
else {
char* buffer = (char*)malloc(sizeof(char)*MSG_SIZE);
if(recv(server_fd, buffer, sizeof(buffer), 0) == 0) {
close(server_fd);
server_fd = 0;
}
else
msgRecvEvent(buffer);
}
}
}
}
}
return 0;
}
Related
I have created a client server application in C (TCP) and my codes are all working find (functions). However, from the client side, when I enter a command, for example "time", the server returns the correct response, but on second time executing the same command, the server returns "invalid command"
This is my server.c, creating of the different threads and all are working perfectly.
void menu(int connfd, int i)
{
while(TRUE)
{
userMenu();
write(connfd, buffer, sizeof(buffer));
//read command
bzero(buffer, MAX);
read(connfd, buffer, MAX);
if (CheckValidCommand(buffer) != TRUE)
{
bzero(buffer, MAX);
strcpy(buffer, "Invalid Command\n");
write(connfd, buffer, sizeof(buffer));
}
else
{
char* token = strtok(buffer, " ");
char command[20];
strcpy(command, ConvertToLower(token));
if (strcmp(command, "join") == 0)
{
Join(connfd, buffer);
}
else if (strcmp(command, "whois") == 0)
{
//Get username
token = strtok(NULL, " ");
bzero(buffer, MAX);
strcpy(buffer, WhoIs(connfd, token));
write(connfd, buffer, sizeof(buffer));
}
else if (strcmp(command, "msg") == 0)
{
//Get username
token = strtok(NULL, " ");
Chat(connfd, token, buffer);
}
else if (strcmp(command, "time") == 0)
{
bzero(buffer, MAX);
strcpy(buffer, GetTime());
write(connfd, buffer, sizeof(buffer));
}
else if (strcmp(command, "alive") == 0)
{
Alive(connfd);
}
else if (strcmp(command, "quit") == 0)
{
Quit(connfd);
}
}
}
CheckConnectedUser();
}
And this is my client.c
int CheckValidCommand(char buff[])
{
int isValid = FALSE;
int wordCount = 0;
char tokens[5][20];
for (int i = 0; i < strlen(buff) - 1; i++)
{
if (buff[i] == ' ')
{
wordCount++;
}
}
wordCount++;
char* token = strtok(buff, " ");
token = ConvertToLower(token);
if (strcmp(token, "join") == 0)
{
int pos = 0;
int totalTokens = 0;
while (token != NULL)
{
if (strlen(token) > 20)
return FALSE;
strcpy(tokens[totalTokens], token);
totalTokens++;
token = strtok(NULL, " ");
}
totalTokens--;
char* Name = malloc(sizeof(char) * 20);
char* Username = malloc(sizeof(char) * 20);
//Get UserName
strcpy(Username, tokens[1]);
strcpy(Name, tokens[2]);
strcat(Name, " ");
//Get name
for (int x = 2; x < totalTokens - 1; x++)
{
strcat(Name, " ");
strcat(Name, tokens[x]);
}
strcat(Name, tokens[totalTokens]);
if (strlen(Name) > 20 || strlen(Username) > 20)
return FALSE;
else
return TRUE;
}
else if (strcmp(token, "whois") == 0)
{
if (wordCount > 2)
return FALSE;
token = strtok(NULL, " ");
if (strlen(token) > 20)
return FALSE;
return TRUE;
}
else if (strcmp(token, "msg") == 0)
{
token = strtok(NULL, " ");
if (strlen(token) > 20)
return FALSE;
char txt[MAX];
while (token != NULL)
{
strcat(txt, token);
strcat(txt, " ");
}
strcpy(txt, RemoveExtraSpace(txt));
if (strlen(txt) > 256)
return FALSE;
return TRUE;
}
else if (strcmp(token, "time") == 0)
{
if (strtok(NULL, " ") == NULL)
return TRUE;
else
return FALSE;
}
else if (strcmp(token, "alive") == 0)
{
if (strtok(NULL, " ") == NULL)
return TRUE;
else
return FALSE;
}
else if (strcmp(token, "quit") == 0)
{
if (strtok(NULL, " ") == NULL)
return TRUE;
else
return FALSE;
}
else
{
return FALSE;
}
}
int main(int argc,char* argv[])
{
if (argc != 3)
{
printf("Run with : \n");
printf("\t./client ip_address port_number\n");
printf("\t\tWhere ipaddress is ipv4 address\n");
printf("\t\tWhere port_number is open port number\n");
}
else
{
int sockfd, connfd, n;
char currChar;
struct sockaddr_in servaddr, cli;
char ipaddress[20];
memcpy(ipaddress, argv[1], strlen(argv[1]));
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed!\n");
exit(0);
}
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, ipaddress, &(servaddr.sin_addr));
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0)
{
printf("connection with the server failed!\n");
exit(0);
}
while (TRUE)
{
//read menu
bzero(buffer, MAX);
read(sockfd, buffer, sizeof(buffer));
printf("%s", buffer);
bzero(buffer, MAX);
n = 0;
while ((buffer[n++] = getchar()) != '\n');
buffer[strcspn(buffer, "\n")] = 0;
write(sockfd, buffer, sizeof(buffer));
//read response
bzero(buffer, MAX);
read(sockfd, buffer, sizeof(buffer));
printf("%s\n", buffer);
}
// close the socket
close(sockfd);
}
return 0;
}
I posted this problem a couple of hours ago, but unfortunately, the details was not clear. i've added the code and some explanation.
i have a string like this to send through socket: "000f45546874684498765" as you see the first 3 numbers are zero, when the C compiler comes to this 000 it thinks these zeros are the finishing of the string. any suggestion?
proc_socketgps(s32 TaskId)
while (1)
{
Ql_Sleep(socket_timer);
if (is_socket_success == TRUE)
{
APP_DEBUG("start socket connect\r\n");
APP_DEBUG("m_tcp_state :%d\r\n", m_tcp_state);
APP_DEBUG("STATE_SOC_SEND :%d\r\n", STATE_SOC_SEND);
APP_DEBUG("m_socketid :%d\r\n", m_socketid);
proc_handle("\x00\x11\x22", sizeof("\x00\x11\x22"));
}
static void proc_handle(unsigned char *pData, s32 len)
char *p = NULL;
s32 iret;
u8 srvport[10];
//command: Set_APN_Param=<APN>,<username>,<password>
p = Ql_strstr(pData, "Set_APN_Param=");
if (p)
{
Ql_memset(m_apn, 0, 10);
if (Analyse_Command(pData, 1, '>', m_apn))
{
APP_DEBUG("<--APN Parameter Error.-->\r\n");
return;
}
Ql_memset(m_userid, 0, 10);
if (Analyse_Command(pData, 2, '>', m_userid))
{
APP_DEBUG("<--APN Username Parameter Error.-->\r\n");
return;
}
Ql_memset(m_passwd, 0, 10);
if (Analyse_Command(pData, 3, '>', m_passwd))
{
APP_DEBUG("<--APN Password Parameter Error.-->\r\n");
return;
}
APP_DEBUG("<--Set APN Parameter Successfully<%s>,<%s>,<%s>.-->\r\n", m_apn, m_userid, m_passwd);
return;
}
//command: Set_Srv_Param=<srv ip>,<srv port>
p = Ql_strstr(pData, "Set_Srv_Param=");
if (p)
{
Ql_memset(m_SrvADDR, 0, SRVADDR_BUFFER_LEN);
if (Analyse_Command(pData, 1, '>', m_SrvADDR))
{
APP_DEBUG("<--Server Address Parameter Error.-->\r\n");
return;
}
Ql_memset(srvport, 0, 10);
if (Analyse_Command(pData, 2, '>', srvport))
{
APP_DEBUG("<--Server Port Parameter Error.-->\r\n");
return;
}
m_SrvPort = Ql_atoi(srvport);
APP_DEBUG("<--Set TCP Server Parameter Successfully<%s>,<%d>.-->\r\n", m_SrvADDR, m_SrvPort);
m_tcp_state = STATE_NW_GET_SIMSTATE;
APP_DEBUG("<--Restart the TCP connection process.-->\r\n");
return;
}
//if not command,send it to server
m_pCurrentPos = m_send_buf;
Ql_strcpy(m_pCurrentPos + m_remain_len, pData);
m_remain_len = Ql_strlen(m_pCurrentPos);
if (!Ql_strlen(m_send_buf)) //no data need to send
break;
m_tcp_state = STATE_SOC_SENDING;
do
{
ret = Ql_SOC_Send(m_socketid, m_pCurrentPos, m_remain_len);
APP_DEBUG("Message Data :%s", m_pCurrentPos);
APP_DEBUG("<--Send data,socketid=%d,number of bytes sent=%d-->\r\n", m_socketid, ret);
if (ret == m_remain_len) //send compelete
{
m_remain_len = 0;
m_pCurrentPos = NULL;
m_nSentLen += ret;
m_tcp_state = STATE_SOC_ACK;
break;
}
else if ((ret <= 0) && (ret == SOC_WOULDBLOCK))
{
//waiting CallBack_socket_write, then send data;
break;
}
else if (ret <= 0)
{
APP_DEBUG("<--Send data failure,ret=%d.-->\r\n", ret);
APP_DEBUG("<-- Close socket.-->\r\n");
Ql_SOC_Close(m_socketid); //error , Ql_SOC_Close
m_socketid = -1;
m_remain_len = 0;
m_pCurrentPos = NULL;
if (ret == SOC_BEARER_FAIL)
{
m_tcp_state = STATE_GPRS_DEACTIVATE;
}
else
{
m_tcp_state = STATE_GPRS_GET_DNSADDRESS;
}
break;
}
else if (ret < m_remain_len) //continue send, do not send all data
{
m_remain_len -= ret;
m_pCurrentPos += ret;
m_nSentLen += ret;
}
} while (1);
break;
the code has been added to the question. firs socket gets open and gets connected to the server. this function >> proc_handle("\x00\x11\x22", sizeof("\x00\x11\x22")); sends hexadecimal string, however i think c consider this part "\x00" as end of the string ! and the data won't be sent ! I already tested that if I remove "\x00" from the row above it works like a charm !
I am developing plugin for Pidgin. I want to share one of my windows that are open on my computer with other user via VNC. When I select the window to be shared and press the button, Pidgin freezes and closes.
Here is working well: opening vnc connection and sends Port name to other users. (but this one for sharing all of screen.)
static void
send_button_cb(GtkButton *button, PidginConversation *gtkconv)
{
gchar *url_vnc;
gchar *url_http;
gchar *joinstr;
int std_out[2];
int autoport = purple_prefs_get_bool(PREF_AUTOPORT);
char x11vnc_port[10] = "0";
if (purple_prefs_get_bool(PREF_X11VNC) && ((x11vnc_pid == 0) || (kill(x11vnc_pid, 0) != 0)))
{
if (purple_prefs_get_bool(PREF_GENPASSWD))
{
readableRandomString(password, 4);
}
else
{
strcpy(password, purple_prefs_get_string(PREF_PASSWD));
}
sprintf(x11vnc_port, "%d", 5900 + purple_prefs_get_int(PREF_PORT));
pipe(std_out);
if ((x11vnc_pid = fork()) == 0)
{
close(1);
close(std_out[0]);
dup2(std_out[1], 1);
close(std_out[1]);
int ret = execlp("x11vnc", "x11vnc", "-shared", "-gui", "tray", "-http", "-viewonly", "-passwd", password, ((autoport) ? "-autoport" : "-rfbport"), x11vnc_port, NULL);
perror("pidgin_vnc:x11vnc");
exit(ret);
}
close(std_out[1]);
port_num = x11vnc_port;
if (fd = fdopen(std_out[0], "r"))
{
while (!feof(fd))
{
if (fscanf(fd, "PORT=%d", &port_num))
break;
}
port_num -= 5900;
//close (fd);
printf("FINI\n");
}
else
{
port_num = x11vnc_port;
}
}
const char *ip;
PurpleStunNatDiscovery *stun_res = purple_stun_discover(NULL);
if (stun_res && stun_res->status == PURPLE_STUN_STATUS_DISCOVERED)
{
printf("STUN mode %d %d\n", stun_res->status, stun_res->type);
ip = purple_network_get_my_ip(-1);
}
else
{
ip = purple_upnp_get_public_ip();
if (ip == NULL)
{
printf("LOCAL mode\n");
ip = purple_network_get_my_ip(-1);
}
else
{
printf("UPNP mode\n");
}
}
url_http = g_strdup_printf("http://%s:%d/", ip, 5800 + port_num);
url_vnc = g_strdup_printf("vnc://invitation:%s#%s:%d", password, ip, port_num);
g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, url_vnc);
joinstr = g_strdup_printf("%s.\ntry %s\nor %s. Password=%s", purple_prefs_get_string(PREF_TEXT), url_vnc, url_vnc, url_http, url_http, password);
gtk_imhtml_append_text(GTK_IMHTML(gtkconv->entry), joinstr, FALSE);
g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "imhtml display vnc\n");
g_signal_emit_by_name(gtkconv->entry, "message_send");
g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "message sent\n");
g_free(url_vnc);
g_free(url_http);
g_free(joinstr);
}
There is a problem in here. When I click to button which is calling this function program crashes when you click the button.(this function for sharing one of my windows that are open on my computer.)
static void
send_button_cb_win(GtkButton *button, PidginConversation *gtkconv)
{
gchar *url_vnc;
gchar *url_http;
gchar *joinstr;
int std_out[2];
int comboBoxSelectedRow = gtk_combo_box_get_active(combo_box);
char *selectedId[1] = {0};
selectedId[0] = ekranIds[0][comboBoxSelectedRow];
int autoport = purple_prefs_get_bool(PREF_AUTOPORT);
char x11vnc_port[10] = "0";
if (purple_prefs_get_bool(PREF_X11VNC) && ((x11vnc_pid == 0) || (kill(x11vnc_pid, 0) != 0)))
{
if (purple_prefs_get_bool(PREF_GENPASSWD))
{
readableRandomString(password, 4);
}
else
{
strcpy(password, purple_prefs_get_string(PREF_PASSWD));
}
sprintf(x11vnc_port, "%d", 5900 + purple_prefs_get_int(PREF_PORT));
pipe(std_out);
if((x11vnc_pid = fork()) == 0)
{
close(1);
close(std_out[0]);
dup2(std_out[1], 1);
close(std_out[1]);
int ret = execlp("x11vnc", "x11vnc", "-id", selectedId[0], "-gui", "-shared", "tray", "-http", "-viewonly", "-passwd", password, ((autoport) ? "-autoport" : "-rfbport"), x11vnc_port, NULL);
perror("pidgin_vnc:x11vnc");
exit(ret);
}
close(std_out[1]);
port_num = x11vnc_port;
if (fd = fdopen(std_out[0], "r"))
{
while (!feof(fd))
{
if (fscanf(fd, "PORT=%d", &port_num))
break;
}
port_num -= 5900;
//close (fd);
printf("FINI\n");
}
else
{
port_num = x11vnc_port;
}
}
const char *ip;
PurpleStunNatDiscovery *stun_res = purple_stun_discover(NULL);
if (stun_res && stun_res->status == PURPLE_STUN_STATUS_DISCOVERED)
{
printf("STUN mode %d %d\n", stun_res->status, stun_res->type);
ip = purple_network_get_my_ip(-1);
}
else
{
ip = purple_upnp_get_public_ip();
if (ip == NULL)
{
printf("LOCAL mode\n");
ip = purple_network_get_my_ip(-1);
}
else
{
printf("UPNP mode\n");
}
}
url_http = g_strdup_printf("http://%s:%d/", ip, 5800 + port_num);
url_vnc = g_strdup_printf("vnc://invitation:%s#%s:%d", password, ip, port_num);
g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, url_vnc);
joinstr = g_strdup_printf("%s.\ntry %s\nor %s. Password=%s", purple_prefs_get_string(PREF_TEXT), url_vnc, url_vnc, url_http, url_http, password);
gtk_imhtml_append_text(GTK_IMHTML(gtkconv->entry), joinstr, FALSE);
g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "imhtml display vnc\n");
g_signal_emit_by_name(gtkconv->entry, "message_send");
g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "message sent\n");
g_free(url_vnc);
g_free(url_http);
g_free(joinstr);
gtk_widget_show_all(button);
}
This function to fill combobox with opened windows names
static void
refresh_combo_box(GtkWidget *widget, PidginConversation *gtkconv)
{
FILE *fp1;
FILE *fp2;
char path[1035];
char path2[1035];
char sum[1035];
/* Open the command for reading. */
fp1 = popen("xprop -root | grep '_NET_CLIENT_LIST_STACKING(WINDOW)'", "r");
if (fp1 == NULL)
{
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path) - 1, fp1) != NULL)
{
// printf("%s", path);
strcat(sum, path);
}
char *splitter = strtok(sum, "#");
splitter = strtok(NULL, "#");
char *virgulSplitter = strtok(splitter, ", ");
ekranIds[0][0] = strdup(virgulSplitter);
int a = 1;
while (virgulSplitter != NULL)
{
virgulSplitter = strtok(NULL, ",");
if (virgulSplitter != NULL)
{
ekranIds[0][a] = strdup(virgulSplitter);
a++;
}
}
for (int x = 0; x < a; x++)
{
ekranIds[0][a - 1][strcspn(ekranIds[0][a - 1], "\n")] = 0;
char tmp[500] = {0};
//here is get window names by id
sprintf(tmp, "xprop -id %s | grep '^WM_NAME'", ekranIds[0][x]);
fp2 = popen(tmp, "r");
if (fp1 == NULL)
{
printf("Failed to run command\n" );
exit(1);
}
// Read the output a line at a time - output it.
while (fgets(path2, sizeof(path2) - 1, fp2) != NULL)
{
char *windowSplitter = strtok(path2, "=");
windowSplitter = strtok(NULL, "=");
ekranIds[1][x] = strdup(windowSplitter);
}
}
pclose(fp2);
pclose(fp1);
char *combobox_source[30];
for (int yf = 0; yf < 30; yf++)
{
if (ekranIds[1][yf] != NULL)
{
combobox_source[yf] = strdup(ekranIds[1][yf]);
}
}
gtk_list_store_clear(GTK_LIST_STORE(gtk_combo_box_get_model(combo_box)));
for (int i = 0; i < G_N_ELEMENTS(combobox_source); i++)
{
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_box), combobox_source[i]);
}
gtk_combo_box_set_active(GTK_COMBO_BOX(combo_box), 0);
gtk_widget_show_all(combo_box);
}
First function is working well: opening vnc connection and sends Port name to other users. (but this one for sharing all of screen.)
Second function has problem. When I click to button which is calling this function program crashes when you click the button.(this function for sharing one of my windows that are open on my computer.)
Third function to fill combobox with opened windows' names.
I have written a function for the purposes of redirecting output from some command to a file. Something like this
ls > ls.txt
Here is the function that does output redirection:
int redirect_output(char* cmdline, char **output_filename) {
int i;
char* args[MAX_ARGS];
// int nargs = get_args(cmdline, args);
for(i = 0; args[i] != NULL; i++) {
// Look for the >
if(!strcmp(args[i], ">")) {
// Get the filename
if(args[i+1] != NULL) {
*output_filename = args[i+1];
} else {
return -1; //syntax error
}
return 1; //there is an >
}
}
return 0; //no redirect
}
The function successfully redirects output from some command to a file, but for some reason it causes other commands to stop working. So for example, my program with redirect_output works for something like ls but it does not work for something like cat ls.txt, if I do not call the function it works for any command. And, by not work it mean it gets stuck. Here are the other important functions.
int get_args(char* cmdline, char* args[])
{
int i = 0;
/* if no args */
if((args[0] = strtok(cmdline, "\n\t ")) == NULL)
return 0;
while((args[++i] = strtok(NULL, "\n\t ")) != NULL) {
if(i >= MAX_ARGS) {
printf("Too many arguments!\n");
exit(1);
}
}
/* the last one is always NULL */
return i;
}
void execute(int output, char *outputefile, char* cmdline)
{
int pid, async;
char* args[MAX_ARGS];
int nargs = get_args(cmdline, args);
if(nargs <= 0) return;
if(!strcmp(args[0], "quit") || !strcmp(args[0], "exit")) {
exit(0);
}
/* check if async call */
if(!strcmp(args[nargs-1], "&")) {
async = 1;
args[--nargs] = 0;
}
else async = 0;
pid = fork();
if(pid == 0) { /* child process */
//if(output)
// freopen(outputefile, "w+", stdout);
execvp(args[0], args);
/* return only when exec fails */
perror("exec failed");
exit(-1);
} else if(pid > 0) { /* parent process */
if(!async) waitpid(pid, NULL, 0);
else printf("this is an async call\n");
} else { /* error occurred */
perror("fork failed");
exit(1);
}
}
And here is my main:
int main (int argc, char* argv [])
{
char cmdline[BUFSIZ];
char *output_filename;
char **args;
int output;
for(;;) {
printf("COP4338$ ");
if(fgets(cmdline, BUFSIZ, stdin) == NULL) {
perror("fgets failed");
exit(1);
}
output = redirect_output(cmdline, &output_filename);
switch(0) {
case -1:
printf("Syntax error!\n");
break;
case 0:
break;
case 1:
printf("Redirecting output to: %s\n", output_filename);
break;
}
execute (output, output_filename, cmdline);
}
return 0;
}
Any help will be much appreciated! Thanks!
After sending "wrong" username - client won't start loop from beginning, actually, there is no server asks:?
Dunno how to handle 3 way client-server message sender for such auth. I must understand this to continue such message receiving in further.
client.c:
int is_authenticated = 0;
size_t sendline_s;
while (!is_authenticated) {
recv(sockfd, recvline, MAXLINE, 0);
printf("%s", "server asks:");
fputs(recvline, stdout);
printf("?> ");
fflush(stdout);
while (fgets(sendline, MAXLINE, stdin) != NULL) {
sendline_s = strlen(sendline);
if (sendline[sendline_s-1] == '\n') {
sendline[sendline_s-1] = '\0';
send(sockfd, sendline, sendline_s+1, 0);
puts("username sended");
break;
}
// handling ^Z (EOF) here
//
}
recv(sockfd, recvline, MAXLINE, 0);
printf("\nawaiting for server ACK\n");
puts(recvline);
if (strcmp(recvline, "ACCEPTED_AUTH") == 0) {
puts("authentication complete successful");
is_authenticated = 1;
}
else {
puts("authentication declined");
}
}
server.c
int is_authenticated = 0;
char *accepted = "ACCEPTED_AUTH";
char *name = "kaldown";
char *wrong = "wrong";
size_t name_s = strlen(name);
size_t accepted_s = strlen(accepted);
size_t wrong_s = strlen(wrong);
while (!is_authenticated) {
send(connfd, name, name_s+1, 0);
puts("authentication request was send");
recv(connfd, buf, MAXLINE, 0);
printf("username was recieved: ");
puts(buf);
if (strcmp(buf, name) == 0) {
puts("hurray");
send(connfd, accepted, accepted_s+1, 0);
is_authenticated = 1;
//break;
}
else {
puts("WRONG NAME");
send(connfd, wrong, wrong_s+1, 0);
}
}
But, If i send right username - it passes the block and everything goes well.
server:
while (!is_authenticated) {
if ((n = recv(connfd, buf, MAXLINE-1,0))== -1) {
perror("recv");
exit(1);
}
else if (n == 0) {
printf("Connection closed\n");
//So I can now wait for another client
break;
}
printf("\n%d truely recieved", n);
buf[n] = '\0';
printf("Server:Msg Received %s\n", buf);
if (strcmp(buf, "DONE") == 0) {
strcpy(buf, "DONE");
if ((send(connfd,buf, strlen(buf),0))== -1)
{
fprintf(stderr, "Failure Sending Message\n");
close(connfd);
break;
}
puts("KONEC");
is_authenticated = 1;
}
else {
if ((send(connfd,buf, strlen(buf),0))== -1)
{
fprintf(stderr, "Failure Sending Message\n");
close(connfd);
break;
}
}
printf("Server:Msg being sent: %s\nNumber of bytes sent: %d\n", buf, strlen(buf));
}
client:
while (!is_authenticated) {
printf("Client: Enter Data for Server:\n");
if (fgets(sendline, MAXLINE-1, stdin) != NULL) {
if (sendline[(strlen(sendline)-1)] == '\n') {
sendline[strlen(sendline)-1] = '\0';
if ((send(sockfd,sendline, strlen(sendline),0))== -1) {
fprintf(stderr, "Failure Sending Message\n");
close(sockfd);
exit(1);
}
else {
printf("Client:Message being sent: %s\n",sendline);
n = recv(sockfd, sendline, sizeof(sendline),0);
if ( n <= 0 )
{
printf("Either Connection Closed or Error\n");
//Break from the While
break;
}
sendline[n] = '\0';
if (strcmp(sendline, "DONE") == 0) {
puts("AUTH PASSED");
is_authenticated = 1;
}
printf("Client:Message Received From Server - %s\n",sendline);
}
}
//EOF
}
}