LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   I/O problem in socket programming (https://www.linuxquestions.org/questions/programming-9/i-o-problem-in-socket-programming-734204/)

goldeneagle1234 06-19-2009 10:28 AM

I/O problem in socket programming
 
the program below is to print the IP address of the connected client on server side
well guys my problem is that when i use cout in for(;;) loop no result is displayed each time a client connects....
Only when i use write() func result is displayed each time a client is connected...

above problem persists only when cout or any of C++ stream object is used in a loop like below
plzzz help

Code:

#include<sys/socket.h>
#include<errno.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<fstream>
#include<iostream>
#define TIME_TO_REFRESH_LOG 60
using namespace std;
int main()
{
        int listenfd=socket(AF_INET,SOCK_STREAM,0);
        if(listenfd==-1)
        {
                perror("server socket");
                exit(1);
        }
        struct sockaddr_in servaddr;
        bzero(&servaddr,sizeof(servaddr));
        servaddr.sin_family=AF_INET;
        servaddr.sin_port=htons(9001);
        servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
        if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))==-1)
        {
                perror("server bind");
                exit(1);
        }
        if(listen(listenfd,128)==-1)
        {
                perror("server listen");
                exit(1);
        }
        int connfd;
        struct sockaddr_in cliaddr;
        socklen_t clilen;
        for(;;)
        {
                bzero(&cliaddr,sizeof(cliaddr));
                clilen=sizeof(cliaddr);
                connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&clilen);               
                if(connfd==-1)
                {
                        perror("server accept");       
                        //continue;
                }
                char buf[100];
                inet_ntop(AF_INET,&cliaddr.sin_addr,buf,sizeof(buf));
                cout<<buf;//not working in loop
                write(1,buf,100);//working
                close(connfd);
        }       
        return 0;
}


bannock 06-19-2009 11:47 AM

Probably cout isn't getting flushed, try this:

Code:

cout << buff << endl;
or
Code:

cout << buff;
flush(cout);


goldeneagle1234 06-19-2009 12:06 PM

thanks
 
thanks man,
the problem had almost bewildered me


All times are GMT -5. The time now is 04:41 AM.