-
winsock problem
I'm getting a "socket not connected" error, but I can't figure out whats wrong with my code.
Server
Code:
#include <winsock2.h>
#include <iostream>
char *welcome = "Test message";
int main()
{
WSADATA WSAdata;
WSAStartup(MAKEWORD(2,2), & WSAdata);
sockaddr_in addr;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(5432);
SOCKET Sock = socket(AF_INET, SOCK_STREAM, 0);
if(bind(Sock, (SOCKADDR*) &addr, sizeof(addr)) == -1)
{
std::cout << "Error in binding\n";
WSACleanup();
return 1;
}
if(listen(Sock,5) == -1)
{
std::cout << "Error in listening\n";
WSACleanup();
return 1;
}
int size = sizeof(addr);
if(accept(Sock, (LPSOCKADDR) &addr, &size) == -1)
{
std::cout << "Failure in connection\n";
WSACleanup();
return 1;
}
std::cout << "Client connected!\n";
std::cout << "Ip: " << inet_ntoa(addr.sin_addr) << "\n";
if(send(Sock, welcome, strlen(welcome) , 0) == -1)
{
std::cout << "Error while sending\n";
std::cout << WSAGetLastError();
WSACleanup();
return 1;
}
else
std::cout << "Sending Message!\n";
shutdown(Sock,2);
WSACleanup();
return 0;
}
Client
Code:
#include <winsock2.h>
#include <iostream>
int main()
{
WSADATA WSAdata;
WSAStartup(MAKEWORD(2,2), & WSAdata);
sockaddr_in client;
client.sin_addr.s_addr = inet_addr("127.0.0.1");
client.sin_family = AF_INET;
client.sin_port = htons(5432);
SOCKET Sock = socket(AF_INET, SOCK_STREAM, 0);
if(connect(Sock, (SOCKADDR*) &client, sizeof(client)) == SOCKET_ERROR)
{
std::cout << "Error in connecting\n";
std::cout << WSAGetLastError();
WSACleanup();
return 1;
}
char buff[40] = "";
if(recv(Sock, buff, strlen(buff), 0) == -1)
std::cout << WSAGetLastError();
WSACleanup();
return 0;
}
Thanks
-
> I'm getting a "socket not connected" error
That doesn't correspond to any of the error messages in your code.
> WSAGetLastError();
This should tell you why - what did you get printed for this when it raised the error?
Go look it up in the manual to find out more.
Do you have a firewall running on your local machine for example?
> if(recv(Sock, buff, strlen(buff), 0) == -1)
buff is "", so strlen buff is 0
Try sizeof(buff) instead
Better yet, use sizeof(buff)-1, so you can append the \0 to make it a proper C string
Code:
if( (n=recv(Sock, buff, sizeof(buff)-1, 0)) != -1) {
buff[n] = '\0';
}
-
Doesn't work. The exact error codes are 10057 for the server, and 10054 for client (I believe this is conn. reset by peer). I don't have a firewall, and as you probably noticed, am just doing this via simple loopback on my own local ip.
-
Thanks for the help. I fixed the problem.