101010110101
101010110101

Reputation: 1998

Client is having trouble connecting to server using sockets?

My server is up and running (connecting through telnet worked so I know its functional) but my client cannot seem to establish a connection. I have a feeling it has something to do with the way I'm filling out the sockaddr_in serverAddr struct.

Can anyone please help? Thank you.

int clientSocket;
char hostname[256];
struct sockaddr_in serverAddr;
struct hostent *host;
socklen_t theirAddrSize;

gethostname(hostname, sizeof(hostname));
host = gethostbyname(hostname);

memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr( host->h_name );
serverAddr.sin_port = htons( 30000 );

if ( clientSocket = socket( AF_INET, SOCK_STREAM , 0 ) == -1) {
    cerr << "socket failed ; exiting..." << endl;
    exit(1);
}

if ( connect( clientSocket , (struct sockaddr *) &serverAddr , sizeof(serverAddr) ) == -1 ) {
    cerr << "connect failed ; exiting..." << endl;
    exit(1);
}

connect always returns -1.

Upvotes: 0

Views: 353

Answers (4)

101010110101
101010110101

Reputation: 1998

I did require the memcpy but alot of this headache stemmed from a very mindless syntax error:

if ( clientSocket = socket( AF_INET, SOCK_STREAM , 0 ) == -1)

I had to wrap the assignment in parenthesis before comparing it to -1.

if (( clientSocket = socket( AF_INET, SOCK_STREAM , 0 )) == -1)

Gah, you live you learn :)

Upvotes: 1

Bob Moore
Bob Moore

Reputation: 6894

As far as I can see there's nothing wrong with the code you've posted here. It's pretty much identical with socket client code I've been writing for years. So the problem either lies elsewhere in the code, or it's in the data.

Ah - you've edited the code... and added some comments. OK, the return value from inet_addr is -1 (4294967295 == 0xFFFFFFFF == -1 == INADDR_NONE), so it doesn't seem to like what you're passing it.

You need to run the code through a debugger, concentrating on the calls to gethostname and gethostbyname. I'm assuming this is test code, since you're connecting to the same machine you're running on.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308520

Instead of inet_addr(host->h_name), use host->h_addr_list[0].

Upvotes: 4

Ewan Todd
Ewan Todd

Reputation: 7312

Does this work?

        memcpy(&serverAddr.sin_addr,
            host->h_addr,
            sizeof(serverAddr.sin_addr));

Upvotes: 3

Related Questions