Sign in to follow this  
Sfpiano

Client error or server

Recommended Posts

I'm trying to getup a basic client-server chat program in winsock, and my client program keeps timging out. Is this a server error, or a client error? Client:
int nret;
	WSADATA wsaData;
	LPHOSTENT hostEntry;

	if( WSAStartup(MAKEWORD(2,0), &wsaData) != NULL ) {
		exit(0);
	}

	hostEntry = gethostbyname("sfpiano.rh.rit.edu");
	fprintf(stdout, "Connecting to: %s", inet_ntoa (*(struct in_addr *)*hostEntry->h_addr_list) );
	if( !hostEntry ) {
		exit(0);
	}

	SOCKET listenSock;
	listenSock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
	if( listenSock == INVALID_SOCKET ) {
		exit(0);
	}

	SOCKADDR_IN serverInfo;
	serverInfo.sin_family = AF_INET;
	serverInfo.sin_addr.s_addr= *((ULONG*)hostEntry->h_addr_list);
	serverInfo.sin_port = htons(5505);

	if( NETFAIL(connect(listenSock, (LPSOCKADDR)&serverInfo, sizeof(sockaddr))) ) {
		exit(0);
	}
Server
int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA wsaData;

	if( WSAStartup(MAKEWORD(1,1), &wsaData) != NULL ) {
		exit(0);
	}

	SOCKET listenSock;
	listenSock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
	if( listenSock == INVALID_SOCKET ) {
		exit(0);
	}

	SOCKADDR_IN serverInfo;
	serverInfo.sin_family = AF_INET;
	serverInfo.sin_addr.s_addr = INADDR_ANY;
	serverInfo.sin_port = htons(5505);

	if( NETFAIL( bind(listenSock, (LPSOCKADDR)&serverInfo, sizeof(sockaddr))) ) {
		exit(0);
	}

	if( NETFAIL( listen(listenSock, 10) ) ) {
		exit(0);
	}

	SOCKET client;
	client = accept(listenSock, NULL, NULL);
	if( client == INVALID_SOCKET ) {
		exit(0);
	}

	cout<<"User Connected\n";

	closesocket(client);
	closesocket(listenSock);

	WSACleanup();
}

Share this post


Link to post
Share on other sites
I couldn't find any obvious errors in the code, but that doesn't say much.
Are you sure that the client can reach the server? Have you tried running it locally (i.e. on loopback only)?
You could also try substituting the client for telnet or use some public web server as server.

Share this post


Link to post
Share on other sites
Ok, I tried telnet-ing into the server and it worked, so I guess the problem lies with the client, but I don't know where. How can I test to see if the client can reach the server? Also, as a clarification, the client and the server should use the same port correct?

Share this post


Link to post
Share on other sites
Apparently if I set the address of the server from the client as
inet_addr("xxx.xxx.xxx.xxx");

instead of:

hostEntry = gethostbyname("server.com");
*((ULONG*)hostEntry->h_addr_list);


it works; can anyone explain this to me?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this