PDA

View Full Version : Problems with Sockets


Dunna
11-29-2007, 04:08 AM
If anyone is proficient in the use of sockets, I could use your help. My problem(s) is the following (on MSVS 2005 C++):

1. I have a client and a server. If I connect to my server while in debug mode and while hosting and joining on my laptop (127.0.0.1:27798), I get the following error: "String is not null terminated". I get that error on the connect() API.

2. If I do the same thing in release mode, it connects successfully.

3. I can't host on another computer on my network, say 192.168.1.102, and connect from my laptop at 192.168.1.101. If I do I get a "Connection refused." or "Connection timed out." error, depending on some very minor changes in the code.

Here's the client:

sockaddr_in info;
in_addr target;
hostent *host;
memset(&info, 0, sizeof(info));

if (ip == NULL)
target.s_addr = inet_addr(DEFAULT_SERVER);
else
target.s_addr = inet_addr(ip);
if (port == -1)
info.sin_port = htons(DEFAULT_PORT);
else
info.sin_port = htons(port);

info.sin_family = AF_INET;
host = gethostbyaddr((const char*)&target, sizeof(sockaddr_in), AF_INET);
info.sin_addr = *((LPIN_ADDR)*host->h_addr_list);

mySocket = socket(AF_INET, SOCK_STREAM, 0);
if (mySocket == INVALID_SOCKET)
{
ERR("SD_NETWORK::Connect: Failed to create socket.");
return SD_CREATE_FAIL;
}

// Time to connect to server
if ( (connect( mySocket, (SOCKADDR*)&info, (int)sizeof(sockaddr_in))) == SOCKET_ERROR )
{
int temp = WSAGetLastError();
char buf[10] = "";
itoa(temp, buf, 10);
ERR(buf);
closesocket(mySocket);
return SD_CONNECT_FAIL;
}


Here's the server:

mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // Create a serving socket
if (mySocket == INVALID_SOCKET)
{
ERR("SD_NETWORK::Listen: Failed to create socket.");
return SD_CREATE_FAIL;
}
// Setup a sockaddr_in structure with IP and port info for listening...
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");

if (port == -1)
addr.sin_port = htons(DEFAULT_PORT);
else
addr.sin_port = htons(port);

//Bind the new structure to the port
if (bind(mySocket, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR)
{
if (port == -1)
{
ERR("SD_NETWORK::Listen: Failed to bind socket.");
closesocket(mySocket);
return SD_BIND_FAIL;
} else
{
//Ok failed on the requested port. Try the default port...
ERR("SD_NETWORK::Listen: Requested port in use. Attempting to connect to default port.");
addr.sin_port = htons(DEFAULT_PORT);
if (bind(mySocket, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR)
{
//No dice. Bail out.
ERR("SD_NETWORK::Listen: Failed to bind socket.");
closesocket(mySocket);
return SD_BIND_FAIL;
}
}
}
//Setup the socket for listening
if (listen(mySocket, SOMAXCONN) == SOCKET_ERROR)
{
ERR("SD_NETWORK::Listen: Failed to listen.");
closesocket(mySocket);
return SD_LISTEN_FAIL;
}