I'm trying to write a program that connects to a server opened with nc -v -l 1337
on another terminal, and redirects stdin, stdout, stderr to the socket.
Meaning, the other terminal will write to the socket, and my program will read it with getchar()
and respond using printf()
.
I came across something strange - everything works fine if I comment out the first use of printf (before dup2(sockfd,1)
). If not, printing does nothing. What can cause this?
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(1337);
connect(sockfd, (SA*)&servaddr, sizeof(servaddr));
dup2(sockfd,0);
//---------------------------
// printf("%s\n","hi" );
//---------------------------
dup2(sockfd,1);
dup2(sockfd,2);
char buff[80];
int n;
while(1){
n = 0;
while ((buff[n++] = getchar()) != '\n');
buff[n-1] = 0;
printf("message %s excepted\n",buff );
}
// close the socket
close(sockfd);
}