getline() function behaves strangly

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • venkata narendr
    New Member
    • Aug 2011
    • 1

    getline() function behaves strangly

    I am trying to emulate telnet functionality by writing a socket listener program, and an application redirecting its console to the listener over sockets.

    On the server side I opened a socket on my local ip, a defined port, and started listening on it like this
    Code:
    sockfd = socket(AF_INET,SOCK_STREAM,0);
    portno = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr);
    listen(sockfd,5);
    neewsockfd = accept(sockfd,(struct sockaddr*)&cli_addr,&clien);
    Then I started reading the incoming data in a seperate thread like this
    Code:
     ...
    while(1)
    {
      bzero(buffer,256);
      n= read(newsockfd,buffer,255);
      if(n>0)
         printf("%s",buffer);
    }
    And in the main routine after the listneing code I added the socket data sending part like this.
    Code:
     ....
    while(1)
    {
       bzero(buffer,256);
       getline(&buffer,&t,stdin);
       n=send(newsockfd,buffer,strlen(buffer),MSG_EOR);
    }
    And for the client part I had connected to the server like this.
    Code:
     ....
    sockfd = socket(AF_INET,SOCK_STREAM,0);
    portno = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    inet_pton(AfF_INET,hostip,&serv_addr.sin_addr.s_addr)
    serv_addr.sin_port = htons(portno);
    connect(sockfd,serv_addr,sizeof(serv_addr));
    And then I duped the stdin, stdout and stderr to sockfd descriptor for redirecting the console as follows.
    Code:
     ....
     dup2(sockfd,STDIN_FILENO);
     dup2(sockfd,STDOUT_FILENO);
     dup2(sockfd,STDERR_FILENO);
    
     close(sockfd);
    And finally I have something like this in client to test the console redirecting
    Code:
     ...
    while(1)
    {
       bzero(mystring,256);
       i = getline(&string,&t,stdin);
       printf("Input:%s-%d\n",mystring,i);
    }
    In the above code I expect the getline to be blocked till I enter some characters on the server application console, but for my agony it comes out with i value 0 repeatedly.

    Any idea why this behavior.
    Last edited by Niheel; Aug 3 '11, 08:26 AM. Reason: fixed code tags :)
Working...