So here is the code for a TCP echo client. When I have the echo server listening on port 5000, the client connects but then once I type a message and hit enter, it disconnects automatically. What's the problem here?
source code(tcp_ec.c):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#define MAX_BUFFER 1024
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
int connector,flags,r;
int port;
struct hostent* host;
struct in_addr in;
struct sockaddr_in rmaddr;
bool connected = false;
char sndbuffer[MAX_BUFFER];
char rcvbuffer[MAX_BUFFER];
char hostname[INET_ADDRSTRLEN];
char* exit = "quit";
if((connector = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
perror("socket");
return -1;
}
printf("\n");
printf("Enter the remote hostname(URL/IP4 address): ");
scanf("%s", hostname);
printf("\n");
printf("Enter the port number you wish to connect(on): ");
scanf("%u", &port);
printf("\n");
if(port==0){
printf("ERR0R: Port number must be between 1 & 65,535\n");
printf("\n");
printf("Enter the port number you wish to connect(on): ");
scanf("%u", &port);
printf("\n");
}
host = gethostbyname(hostname);
if(host==NULL){
perror("hostname");
return -1;
}
bzero(&rmaddr,sizeof(rmaddr));
rmaddr.sin_family = AF_INET;
rmaddr.sin_port = htons(port);
bcopy((char*)host->h_addr, (char*)&rmaddr.sin_addr.s_addr, host->h_length);
if(connect(connector,(struct sockaddr*)&rmaddr,sizeof(rmaddr))<0){
perror("connect");
return -1;
}else{
connected=true;
printf("\n");
printf("Connected to host: %s",hostname,"on port %u",port);
printf(" type 'quit' to disconnect\n");
printf("\n");
}
while(connected==true){
printf(">");
scanf("%s",sndbuffer);
printf("\n");
if(sndbuffer==exit){
close(connector);
connected = false;
return 0;
}
if(send(connector,(void*)sndbuffer,sizeof(sndbuffer),MSG_EOR||MSG_NOSIGNAL)<0){
perror("send");
close(connector);
return -1;
}
if(recv(connector,(void*)rcvbuffer,sizeof(rcvbuffer),MSG_EOR||MSG_NOSIGNAL)<0){
perror("recv");
close(connector);
return -1;
}else{
printf(">>");
printf("%s\n",rcvbuffer);
printf("\n");
}
}
}
The console output(program output file is "tc"):
zermacr0yd@DALEK /usr/lib/gcc/x86_64-linux-gnu/4.7.3/include $ ./tec
Enter the remote hostname(URL/IP4 address): 127.0.0.1
Enter the port number you wish to connect(on): 5000
Connected to host: 127.0.0.1 type 'quit' to disconnect
>asssr
sendmsg: Broken pipe
zermacr0yd@DALEK /usr/lib/gcc/x86_64-linux-gnu/4.7.3/include $
This is done when the echo_server is running on port 5000.