LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   char array wont display what it reads from the connected descriptor (https://www.linuxquestions.org/questions/programming-9/char-array-wont-display-what-it-reads-from-the-connected-descriptor-899749/)

TAN 08-27-2011 01:23 AM

char array wont display what it reads from the connected descriptor
 
This is my code. accept returns the connected descriptor but in the read function the buffer(array) contains some garbage values. I am trying to capture the request made by the browser. I have configured the proxy so it will connect to the desired port. please help

#include <arpa/inet.h>


#include <stdio.h>

#include <time.h>

#include <string.h>

#include <errno.h>

#include <netdb.h>

#include <sys/uio.h>

#include <arpa/inet.h>

#include <netinet/in.h>

#include <sys/types.h>

#include <sys/socket.h>




int

main(int argc, char **argv)

{

int listenfd, connfd,n,x;

socklen_t len;

struct sockaddr_in servaddr, cliaddr;

char buff[1501];

time_t ticks;

int yes = 1;

const char *ptr;



if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ){

fprintf(stderr, "socket creation failed\n");

exit (1);

}



bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family = AF_INET;

if (inet_pton(AF_INET,"127.0.0.1", &servaddr.sin_addr) <= 0){

printf("inet_pton error for %s", argv[1]);

return 1;

}

servaddr.sin_port = htons(4616); /* daytime server */



if ( (bind(listenfd, (SA *) &servaddr, sizeof(servaddr))) < 0) {

fprintf(stderr, "bind failed\n");

exit (1);

fprintf(stderr, "binded\n");

}



if ( listen(listenfd, LISTENQ) < 0) {

fprintf(stderr, "listen failed\n");

exit (1);

fprintf(stderr, "listning\n");

}





//for ( ; ; ) {

len = sizeof(cliaddr);

if ( (connfd = accept(listenfd, (SA *) &cliaddr, &len)) < 0 ) {

fprintf(stderr, "accept failed\n");

exit (1);

}

fprintf(stdout, "accepted\n");

//}



for(;;){

while ( n=read(connfd,buff,1500) > 0) {

buff[n]=0;



printf("%s \n",buff);

if (fputs(buff, stdout) == EOF) {

printf("fputs error");



return 1;

}

printf("[%s] \n",buff);

}

}



if (n < 0) {

printf("read error");

return 1;

}







if ( close(connfd) == -1) {

fprintf(stderr, "accept failed\n");

exit (1);

}



close(listenfd);

return 0;

}

kumawat10 08-27-2011 01:54 AM

Initialize the buffer with " "

char buff[1501] = " ";

TAN 08-27-2011 10:13 AM

I tried., but its not working, I thing something is wrong in the read function

jschiwal 08-28-2011 10:20 PM

Moved: This thread is more suitable in Programming and has been moved accordingly to help your question get the exposure it deserves.


All times are GMT -5. The time now is 05:31 AM.