Hi,
I tried to post this problem in my other thread, but although I keep seeing the 'new posts' icon there are none, so I am going to try and repost this. Also I think since this is a different problem I should make a new thread, I'm sorry if I shouldn't do this but as far as I know I am following the rules.
I wrote a simple echo client in c++, but it keeps crashing whilst calling connect(). I have checked a few examples of other echo clients online, but cannot see what I am missing that theirs has. I am pretty lost so any hints or help would be very appreciated.
Here is the code for my client:Quote:
Could not connect to remote host.
connect: Socket operation on non-socket
Calef13Code:#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define DEST_IP "127.0.0.1"
#define MAX 1024
using namespace std;
int main()
{
char buf[MAX];
struct sockaddr_in dest_addr;
int sock, len, check_recv, check_send;
if ( sock=socket(PF_INET, SOCK_STREAM, 0 ) == -1 )
{
cout<<"Error, could not open socket\n";
}
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(31337);
dest_addr.sin_addr.s_addr = inet_addr(DEST_IP);
memset( dest_addr.sin_zero, '\0', sizeof( dest_addr.sin_zero ) );
if (( connect( sock, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in))) == -1 )
{
cout<<"Could not connect to remote host.\n";
perror("connect");
}
cin.getline( buf, MAX, '\n' );
len = sizeof(buf);
while(1)
{
check_send=send( sock, buf, len, 0 );
switch ( check_send )
{
case -1:
cout<<"Error sending, bailing out...\n";
break;
default:
cout<<check_send<<"Bytes sent\n";
break;
}
check_recv=recv( sock, buf, MAX, 0 );
switch ( check_recv )
{
case 0:
cout<<"Remote host closed connection.\n";
break;
case -1:
cout<<"Error receiving data.\n";
break;
default:
cout<<check_recv<<"Bytes received.\n";
break;
}
}
close(sock);
}