tags:

views:

155

answers:

4

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.

+3  A: 

Does this work?

        memcpy(&serverAddr.sin_addr,
            host->h_addr,
            sizeof(serverAddr.sin_addr));
Ewan Todd
thank you, you're right.
outsyncof
I followed the flow near the gethostbyname() call in this example: http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzab6/rzab6xconoclient.htm
Ewan Todd
+1  A: 

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.

Bob Moore
+4  A: 

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

Mark Ransom
Yes, `inet_addr` is for converting a string like `"127.0.0.1"` into a `struct in_addr`, but the `gethostbyname` has already produced `struct in_addr`s in the `h_addr_list` array.
caf
+1  A: 

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 :)

outsyncof
You should *also* be doing the `memcpy` described by Ewan Todd instead of calling `inet_addr`.
caf