Hello all,
This may sound pretty basic stuff.. but I'm working on a socket example
whose client seems to work fine, but the server doesn't send to the
client the expected result. The problem is that I want to trace what
the server socket is doing, but I'm unable to see any of my fprintf or
printf stuff.
Please take a look to the example:
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
//x ------------------------------------------------------------ x
#define MAXLINE 4096 /* max text line length */
int main(int argc, char **argv)
{
int listenfd, connfd; // socket file descriptor
struct sockaddr_in servaddr; // IPv4 socket address structure
char buff[MAXLINE];
// ********************
char file[32];
FILE *fp;
strcpy(file,"output.txt");
if ((fp = fopen(file, "w")) == NULL)
{
printf("Can't open %s\n", file);
exit(1);
}
else
fprintf(fp, "\nFirst step...");
// ********************
listenfd = socket(AF_INET, SOCK_STREAM, 0); // call to socket function
bzero(&servaddr, sizeof(servaddr)); // initialization of socket
structure to 0
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(9877); // Port in host byte order must be
converted
// to network byte order
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
// INADDR_ANY - wild card
// This tells the kernel to choose the IP address
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
fprintf(fp, "\nWaiting for connection, BEFORE call to listen()");
listen(listenfd, 5);
fprintf(fp, "\nWaiting for connection, AFTER call to listen()");
for ( ; ; ) {
if (connfd = accept (listenfd, NULL, NULL) < 0)
fprintf(fp, "\nERROR on accept");
else
fprintf(fp, "\nSUCCESS on accept");
// We are not interested in knowing the identity of the client
// Therefore, 2nd and 3rd param. to NULL
strcpy(buff, "Output to the client");
snprintf(buff, sizeof(buff), "%%" );
write(connfd, buff, strlen(buff));
close(connfd);
}
// exit(0);
// ********************
fclose(fp);
// ********************
}
As you can see, there are many fprintf instructions which work fine in
my socket client but not in the server. I guess I'm missing some
conceptual stuff here. Any idea?
Thanks!
Fernando