I'm trying to parse the received data from a client in a server. The server have to send back a message according to what the client sent before. But I can not make the strncmp function compare the strings. It always get to the else and my server close the conection. Also my client stays connected and print in screen the option I typed.
Please need help to understand what is wrong!
Thanks!
Incorrect Inputclose error: Bad file descriptor
Program exited with code 01.
void
result(int sockfd)
{
ssize_t n;
char buf[MAXLINE];
int temp;
time_t ticks;
int i;
again:
while ((n =read(sockfd, buf, 15)> 0))
{
buf[n] = '\0';
printf("Message Recieved:%s\n",buf);
srand (time(NULL));
temp = rand() % 15+1;
printf("Ramdom es %i\n",temp);
if ((strncmp (buf,"A",1) == 0) || (strncmp (buf,"a",1) == 0))
{
snprintf(buf, sizeof(buf), "You chose option A -%i times on %.24s\r\n", temp,ctime(&ticks));
Writen(sockfd, buf, n);
}
if ((strncmp (buf,"B",1) == 0) || (strncmp (buf,"b",1) == 0))
{
snprintf(buf, sizeof(buf), "You chose option B -%i times on on %.24s\r\n", temp,ctime(&ticks));
Writen(sockfd, buf, n);
}
else
{
printf("Incorrect Input");
Close(sockfd);
break;
}
}
if (n < 0 && errno == EINTR)
goto again;
else if (n < 0)
err_sys("read error");
}
int
main(int argc, char **argv)
{
int listenfd, connfd;
socklen_t len;
struct sockaddr_in servaddr, cliaddr;
char buff[MAXLINE];
/*char message[MAXLINE];*/
char recvline[MAXLINE + 1];
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);/*----------------------------------------------------*/
servaddr.sin_port = htons(5678);
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
printf("EDMTS is running on 129.128.4.80, listening on port 5678\n");
printf("\n");
printf("Waiting for incoming connections...Press Ctrl+C to end server\n");
for ( ; ; )
{
len = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &len);
/*Client connects to server*/
printf("\n");
printf("Connection from %s, port %d\n",
Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),
ntohs(cliaddr.sin_port));
result(connfd);
Close(connfd);
}
}
With a little logic
if ((strncmp (buf,"B",1) == 0) || (strncmp (buf,"b",1) == 0))
{
snprintf(buf, sizeof(buf), "You chose option B -%i times on on %.24s\r\n", temp,ctime(&ticks));
Writen(sockfd, buf, n);
}
else
{
printf("Incorrect Input");
Close(sockfd);
break;
}
Is where the else lies.
I.e.
it gets run when after it is hits this:
if ((strncmp (buf,"A",1) == 0) || (strncmp (buf,"a",1) == 0))
{
snprintf(buf, sizeof(buf), "You chose option A -%i times on %.24s\r\n", temp,ctime(&ticks));
Writen(sockfd, buf, n);
}
BTW use toupper
http://www.cplusplus.com/reference/cctype/toupper/
i.e.
if ('B' == toupper(buf[0]) ...
Just add another ELSE!