Hi I have been trying for a while to make a win32 app client be able to talk to a server app that I put on my friends computer. I am not 100% sure if the problem is caused by the fact that I have two routers which may interfere with my IP address. The following code works on my LAN and with the loop back address 127.0.0.1.
I am gonna put up the parts that have to do with winsock since it is using SDL/C++/winsock
For the client
bool ConnectToHost( int PortNo, char* IPAddress )
{
WSADATA wsadata;
int error = WSAStartup( 0x0202, &wsadata );
if( error )
{
return false;
}
if( wsadata.wVersion != 0x0202 )
{
WSACleanup();
return false;
}
SOCKADDR_IN target;
target.sin_family = AF_INET;
target.sin_port = htons( PortNo );
target.sin_addr.s_addr = inet_addr( IPAddress );
//s = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
s = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if( s == INVALID_SOCKET )
{
return false;
}
if( connect( s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR )
{
return false;
}
WSAAsyncSelect (s, hwnd, 1045, FD_READ | FD_CONNECT | FD_CLOSE);
return true;
}
and for the server
bool ListenOnPort( int PortNo )
{
WSADATA w;
int error = WSAStartup ( 0x0202, &w );
if( error )
{
return false;
}
if( w.wVersion != 0x0202 )
{
WSACleanup();
return false;
}
SOCKADDR_IN addr;
addr.sin_family = AF_INET;
addr.sin_port = htons( PortNo );
addr.sin_addr.s_addr = htonl( INADDR_ANY );
//s = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
s = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if( s == INVALID_SOCKET )
{
return false;
}
if( bind( s, (LPSOCKADDR)&addr, sizeof(addr)) == SOCKET_ERROR )
{
return false;
}
listen( s, SOMAXCONN );
WSAAsyncSelect(s, hwnd, 1045, FD_READ | FD_CONNECT | FD_CLOSE | FD_ACCEPT);
return true;
}
for my message handler
(not sure why the formatting is all messed up)
switch(message)
{
//Winsock related message...
case 1045:
switch (lParam)
{
case FD_CONNECT: //Connected OK
break;
case FD_CLOSE: //Lost connection
SDL_WM_SetCaption( "SPONG - LISTENER (Connection Lost)", NULL );
CloseConnection();
ListenOnPort(6221);
break;
case FD_READ:
{
char buffer[80];
string strbuff;
memset(buffer, 0, sizeof(buffer));
recvfrom(s, buffer, sizeof(buffer)-1, 0, (SOCKADDR *)&from, &fromlen);
strbuff = buffer;
if( strbuff.length() > 0 )
{
addMessage(strbuff);
}
}
break;
case FD_ACCEPT:
{
SOCKET TempSock = accept(s, (SOCKADDR *)&from, &fromlen);
s = TempSock;
}
break;
}
break;
at the start of the program I have
ListenOnPort(6221);
for the server and
ConnectToHost(6221, "MY.FRIENDS.IP.ADDRESS");
as I said above if I use "127.0.0.1" or my IP on LAN it works perfect however I cannot connect or be connected to from outside of my network.
Any help would be great. If you want are willing to really help me out I the full source for both the client and server are included however you might have to set up the links in to the SDL lib, just ask and I'll be happy to send it.
Again thanks.