For my project I am unable to debug the program so i cannot be sure as to why this error occurs.
My server, which is hosted on c# is failing to connect to server on localhost.
Instead of it sending back a "connection" signal to my server, it never connects, I think the code is written well and I can't see any errors, maybe i made a careless mistake somewhere
Also, I HAVE to use gethostbyname instead of getaddrinfo
winsock namespace:
SOCKET WinSock::ConnectToServer(PCHAR IP, USHORT Port)
{
WSADATA WSA;
if (WSAStartup(MAKEWORD(2, 0), &WSA))
{
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s != SOCKET_ERROR)
{
hostent *Host = gethostbyname(IP);
if (Host != ERROR)
{
SOCKADDR_IN Addr;
Addr.sin_family = AF_INET;
Addr.sin_port = htons(Port);
Addr.sin_addr.s_addr = NULL;
if (bind(s, PSOCKADDR(&Addr), sizeof(Addr)) > 0)
{
return s;
}
}
}
}
return FALSE;
}
BOOL WinSock::SendData(SOCKET s, PBYTE Packet)
{
DWORD PacketSize = lstrlenA(PCHAR(Packet));
if (send(s, PCHAR(&PacketSize), 8, 0) > NULL)
{
if (send(s, PCHAR(Packet), PacketSize, 0) > NULL)
{
return TRUE;
}
}
return FALSE;
}
main method:
int main()
{
char key = 1;
SOCKET S = WinSock::ConnectToServer(0, 55480);
while(true)
{
WinSock:SendData(S, (PBYTE)key);
}
}
if (bind(s, PSOCKADDR(&Addr), sizeof(Addr)) > 0)
The description of this code is that it is supposed to connect to a server. But the problem is that bind() does not connect to any server. It only links the socket to a local port. This is what servers that listen on sockets do. This is, presumably, the same port that the server already opened, hence the bind() fails. If the server wasn't listening bind() will, ironically, succeed. But it won't be connect to anything, anyway.
You want to use connect() and not bind().
Additionally, I have to note that if this function creates a socket first, but then fails to establish a connection for this or any other reason it will return an error indication but fail to close the socket, thus leaking a socket descriptor. You must fix this bug, too.
You are not actually making a connection to the server. You are calling bind() to bind the client socket to a local port 55480, but that does not create a connection. You need to instead call connect() to connect the client socket to the remote port 55480.
Also, your SendData() is coded wrong. It is telling send() to send 8 bytes for the PacketSize, but a DWORD is only 4 bytes in size. And send() does not return NULL on failure. And send() is not guaranteed to send all of the requested bytes, so you need to call it in a loop. And it is customary to send multi-byte integers in network byte order (big endian).
Also, you have coded SendData() to expect a null-terminated C-style string, but that is not what your main() is actually passing in to it.
Try something more like this:
bool WinSock::Init()
{
WSADATA WSA;
return (WSAStartup(MAKEWORD(2, 0), &WSA) == 0);
}
bool WinSock::Cleanup()
{
return (WSACleanup() == 0);
}
SOCKET WinSock::ConnectToServer(const char *IP, unsigned short Port)
{
hostent *Host = gethostbyname(IP);
if ((Host != NULL) && (Host->h_addrtype == AF_INET)
{
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s != INVALID_SOCKET)
{
SOCKADDR_IN Addr = {};
Addr.sin_family = AF_INET;
Addr.sin_port = htons(Port);
Addr.sin_addr.s_addr = * (u_long*) Host->h_addr;
if (connect(s, PSOCKADDR(&Addr), sizeof(Addr)) != SOCKET_ERROR)
{
return s;
}
closesocket(s);
}
}
return INVALID_SOCKET;
}
bool WinSock::Close(SOCKET s)
{
return (closesocket(s) == 0);
}
bool WinSock::SendData(SOCKET s, const void* Data, DWORD DataSize)
{
const char *ptr = (const char*) Data;
while (DataSize > 0)
{
int numSent = send(s, ptr, DataSize, 0);
if (numSent == SOCKET_ERROR) return false;
ptr += numSent;
DataSize -= numSent;
}
return true;
}
bool WinSock::SendData(SOCKET s, const char *Packet)
{
DWORD PacketSize = lstrlenA(Packet);
DWORD tmp = htonl(PacketSize);
if (!SendData(s, &tmp, sizeof(tmp)) return false;
return SendData(s, Packet, PacketSize);
}
int main()
{
if (WinSock::Init())
{
const char *key = "1";
SOCKET S = WinSock::ConnectToServer(NULL, 55480);
if (s != INVALID_SOCKET)
{
while (true)
{
WinSock:SendData(S, key);
}
WinSock::Close(s);
}
WinSock::Cleanup();
}
return 0;
}
Related
I created two win32 server c++ projects both will do similar task like listen for IPC connection from client. both will listen in different port numbers like 1000 and 2000, I'm able to connect first started application like 1000 or 2000 but not both, every second connection request will through timeout at client side.
Below I added my client and server code, I have two server applications with different port no (1000 and 2000) and two client applications which connect to 1000 and 2000 port server app.
Both server apps will go for listening mode but one only take connection request another will throw timeout at client application. if any suggestion please update your comments.
Client Code :
void Initialize()
{
WSADATA WSAData;
WSAStartup(MAKEWORD(2, 2), &WSAData);
}
SOCKET CloseSocket(SOCKET _Socket)
{
/*A shutdown() closes SOCK_STREAM sockets gracefully. Both processes can acknowledge that they are no longer sending. OR Disable sends and/or receives on a socket*/
shutdown(_Socket,SD_BOTH);
/*The closesocket function closes an existing socket.*/
closesocket(_Socket);
return _Socket = INVALID_SOCKET;
}
SOCKET Connect( SOCKET _Socket,
SOCKADDR_IN _Addres )
{
int connectResult = connect(_Socket,(struct sockaddr *)&_Addres,sizeof(_Addres));
if(connectResult == SOCKET_ERROR)
{
_Socket = CloseSocket(_Socket);
}
else if(connectResult == ETIMEDOUT)
{
_Socket = CloseSocket(_Socket);
}
return _Socket;
}
SOCKET ClientSocketPipline(SOCKET _Socket)
{
/*Socket types are defined in sys/socket.h. These types--SOCK_STREAM, SOCK_DGRAM, or SOCK_RAW--are supported by AF_INET and AF_UNIX. The following creates a stream socket in the Internet domain:*/
if ((_Socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
return _Socket = CloseSocket(_Socket);
}
struct timeval timeout;
memset(&timeout,0,sizeof(timeout));
timeout.tv_sec = 2;
timeout.tv_usec = 0;
if ( setsockopt (_Socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0 &&
setsockopt (_Socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0 )
{
return _Socket = CloseSocket(_Socket);
}
return _Socket;
}
void ClientConnectionCall()
{
SOCKET ConnectSocket;
ConnectSocket = INVALID_SOCKET;
ConnectSocket = ClientSocketPipline(ConnectSocket);
SOCKADDR_IN SocketAddres;
memset(&SocketAddres,0,sizeof(SocketAddres));
/*Convert IPv4 and IPv6 addresses from text to binary form*/
if(inet_pton(AF_INET,"192.160.1.1", &SocketAddres.sin_addr.s_addr)>0)
{
SocketAddres.sin_port = htons(1000); // and 2000
SocketAddres.sin_family = AF_INET;
ConnectSocket = Connect(ConnectSocket, SocketAddres);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Initialize();
ClientConnectionCall();
return 0;
}
Server Code listener (Port no : 1000) :
SOCKET ServerClass::CloseSocket(SOCKET _Socket)
{
/*A shutdown() closes SOCK_STREAM sockets gracefully. Both processes can acknowledge that they are no longer sending. OR Disable sends and/or receives on a socket*/
shutdown(_Socket,SD_BOTH);
/*The closesocket function closes an existing socket.*/
closesocket(_Socket);
return _Socket = INVALID_SOCKET;
}
SOCKET ServerClass::Bind(SOCKET _Socket, SOCKADDR_IN _Address)
{
/*bind : Associate a local address with a socket.*/
if(::bind(_Socket,(struct sockaddr*)&_Address,sizeof(_Address)) == SOCKET_ERROR)
{
_Socket = CloseSocket(_Socket);
}
return _Socket;
}
SOCKET ServerClass::ServerSocketPipline(SOCKET _Socket,int _Type)
{
/*Socket types are defined in sys/socket.h. These types--SOCK_STREAM, SOCK_DGRAM, or SOCK_RAW--are supported by AF_INET and AF_UNIX. The following creates a stream socket in the Internet domain:*/
if ((_Socket = socket(AF_INET, _Type, 0)) < 0)
{
return _Socket = CloseSocket(_Socket);
}
int opt = 1;
/* Set socket keep connections alive */
if (setsockopt(_Socket,SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) == SOCKET_ERROR)
{
return _Socket = CloseSocket(_Socket);
}
return _Socket;
}
SOCKET ServerClass::CreateSocket(SOCKET _Socket, int _Port)
{
_Socket = INVALID_SOCKET;
_Socket = ServerSocketPipline(_Socket, SOCK_STREAM);
SOCKADDR_IN SocketAddres;
memset(&SocketAddres,0,sizeof(SocketAddres));
SocketAddres.sin_addr.s_addr = htonl(INADDR_ANY);
SocketAddres.sin_port = htons(_Port);
SocketAddres.sin_family = AF_INET;
//Associate a local address with a socket.
_Socket = Bind( _Socket, SocketAddres );
/*Establish a socket to listen for incoming connection*/
if(::listen(_Socket, 5) != SOCKET_ERROR)
{
//Socket listen success.
}
else
{
//Socket listen failed.
_Socket = SOCKET_ERROR;
}
return _Socket;
}
DWORD WINAPI ServerClass::SocketListener(LPVOID threadParam)
{
if(threadParam != NULL)
{
ServerClass *thisClass = (ServerClass *)threadParam;
SOCKET tempSocket = INVALID_SOCKET;
socklen_t addrlen = sizeof(struct sockaddr_in);
SOCKADDR_IN SocketAddres;
memset(&SocketAddres,0,sizeof(SocketAddres));
SocketAddres.sin_addr.s_addr = htonl(INADDR_ANY);
SocketAddres.sin_port = htons(1000);
SocketAddres.sin_family = AF_INET;
if(thisClass->m_BindSock != INVALID_SOCKET)
{
/*Accept a connection on a socket.*/
tempSocket = ::accept( thisClass->m_BindSock, (struct sockaddr*)&SocketAddres, &addrlen);
if(tempSocket != INVALID_SOCKET)
{
SetEvent(thisClass->m_SocketThreadHandle);
}
else
{
tempSocket = thisClass->CloseSocket(tempSocket);
SetEvent(thisClass->m_SocketThreadHandle);
}
}
}
return 0;
}
ServerClass::ServerMainCall(void)
{
Initialize();
m_BindSock = CreateSocket(m_BindSock,1000);
m_SocketThreadHandle = CreateThread(NULL, 0, SocketListener, this, 0, NULL);
WaitForSingleObject(m_SocketThreadHandle,INFINITE);
int msgboxID = MessageBox( NULL, L"Connection request received from first client", L"",
MB_ICONEXCLAMATION | MB_OK );
}
Server Code listener (Port no : 2000) :
SOCKET ServerClass::CloseSocket(SOCKET _Socket)
{
/*A shutdown() closes SOCK_STREAM sockets gracefully. Both processes can acknowledge that they are no longer sending. OR Disable sends and/or receives on a socket*/
shutdown(_Socket,SD_BOTH);
/*The closesocket function closes an existing socket.*/
closesocket(_Socket);
return _Socket = INVALID_SOCKET;
}
SOCKET ServerClass::Bind(SOCKET _Socket, SOCKADDR_IN _Address)
{
/*bind : Associate a local address with a socket.*/
if(::bind(_Socket,(struct sockaddr*)&_Address,sizeof(_Address)) == SOCKET_ERROR)
{
_Socket = CloseSocket(_Socket);
}
return _Socket;
}
SOCKET ServerClass::ServerSocketPipline(SOCKET _Socket,int _Type)
{
/*Socket types are defined in sys/socket.h. These types--SOCK_STREAM, SOCK_DGRAM, or SOCK_RAW--are supported by AF_INET and AF_UNIX. The following creates a stream socket in the Internet domain:*/
if ((_Socket = socket(AF_INET, _Type, 0)) < 0)
{
return _Socket = CloseSocket(_Socket);
}
int opt = 1;
/* Set socket keep connections alive */
if (setsockopt(_Socket,SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) == SOCKET_ERROR)
{
return _Socket = CloseSocket(_Socket);
}
return _Socket;
}
SOCKET ServerClass::CreateSocket(SOCKET _Socket, int _Port)
{
_Socket = INVALID_SOCKET;
_Socket = ServerSocketPipline(_Socket, SOCK_STREAM);
SOCKADDR_IN SocketAddres;
memset(&SocketAddres,0,sizeof(SocketAddres));
SocketAddres.sin_addr.s_addr = htonl(INADDR_ANY);
SocketAddres.sin_port = htons(_Port);
SocketAddres.sin_family = AF_INET;
//Associate a local address with a socket.
_Socket = Bind( _Socket, SocketAddres );
/*Establish a socket to listen for incoming connection*/
if(::listen(_Socket, 5) != SOCKET_ERROR)
{
//Socket listen success.
}
else
{
//Socket listen failed.
_Socket = SOCKET_ERROR;
}
return _Socket;
}
DWORD WINAPI ServerClass::SocketListener(LPVOID threadParam)
{
if(threadParam != NULL)
{
ServerClass *thisClass = (ServerClass *)threadParam;
SOCKET tempSocket = INVALID_SOCKET;
socklen_t addrlen = sizeof(struct sockaddr_in);
SOCKADDR_IN SocketAddres;
memset(&SocketAddres,0,sizeof(SocketAddres));
SocketAddres.sin_addr.s_addr = htonl(INADDR_ANY);
SocketAddres.sin_port = htons(2000);
SocketAddres.sin_family = AF_INET;
if(thisClass->m_BindSock != INVALID_SOCKET)
{
/*Accept a connection on a socket.*/
tempSocket = ::accept( thisClass->m_BindSock, (struct sockaddr*)&SocketAddres, &addrlen);
if(tempSocket != INVALID_SOCKET)
{
SetEvent(thisClass->m_SocketThreadHandle);
}
else
{
tempSocket = thisClass->CloseSocket(tempSocket);
SetEvent(thisClass->m_SocketThreadHandle);
}
}
}
return 0;
}
ServerClass::ServerMainCall(void)
{
Initialize();
m_BindSock = CreateSocket(m_BindSock,2000);
m_SocketThreadHandle = CreateThread(NULL, 0, SocketListener, this, 0, NULL);
WaitForSingleObject(m_SocketThreadHandle,INFINITE);
int msgboxID = MessageBox( NULL,L"Connection request received from second client",L"",
MB_ICONEXCLAMATION | MB_OK);
}
Finally found the answer to the problem. The issue is because of the firewall blocking at server machine side. After disable it, things started working, for more details please go to the below link:
What can be the reasons of connection refused errors?
I have 2 questions:
first - I try to connect one client to server each time. (the accept function is in thread) but the connection fail in accept - return always -1 (instead of zero).
the second question - how I can add timeout for to accepting client?
server.h
class Server{
public:
void open(int port, object&);
void startThreadOPeration();
void stop(){};
~Server();
private:
sockaddr_in address;
int socketfd;
Object* obj;
void startThread();
std::thread acceptClient;
};
server.cpp
void Server::open(int port,Object& obj) {
this->obj = &obj;
int socketfd = socket(AF_INET, SOCK_STREAM, 0);
if (socketfd == -1) {
throw "Could not create a socket";
}
this->socketfd = socketfd;
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
this->address = address;
if (bind(socketfd, (struct sockaddr *) &this->address, sizeof(this->address)) == -1) {
throw "Could not bind the socket to an IP";
}
if (listen(this->socketfd, 5) == -1) {
throw "Error during listening command";
} else {
std::cout<<"Server is now listening ..."<<std::endl;
}
startThread();
}
void Server::startThreadOPeration() {
while (!side_server::stop) {
// accepting a client
int client_socket = accept(this->socketfd, (struct sockaddr *) &this->address,
(socklen_t *) &this->address); // Return -1
if (client_socket == -1) {
throw "Error accepting client";
}
//do operation
}
void Server::startThread() {
acceptClient = std::thread(&Server::startThreadOPeration,this);
}
Server::~Server(){
close(this->socketfd);
if(acceptClient.joinable()){
this->acceptClient.join();
}
}
thank you for help!
accept() takes 3 parameters - a socket, a pointer to a socket address structure, and a pointer to a socklen_t containing the maximum length of the given socket address structure. On success, the socklen_t will be updated with the actual length of the socket structure.
Unfortunately, your code calls accept() with the address of the this->address variable in the 3rd parameter rather than the address of a valid socklen_t variable. Odds are good this causes this->address to contain what will appear to be complete nonsense when accept() updates what it thinks is a socklen_t but really isn't.
void Server::startThreadOPeration() {
while (!side_server::stop) {
// accepting a client
socklen_t len = sizeof(this->address); // max size of address structure
int client_socket = accept(this->socketfd,
(struct sockaddr *) &this->address,
&tlen); // supply valid max length
if (client_socket == -1) {
throw "Error accepting client";
}
//do operation
}
accept() doesn't do timeouts easily, but select() does:
void Server::startThreadOPeration() {
while (!side_server::stop) {
fd_set readfds;
struct timeval tv;
int result;
FD_ZERO(&readfds);
tv.tv_sec = timeout_s; // number of seconds to wait here
tv.tv_usec = timeout_us; // number of additional us to wait here
FD_SET(this->socketfd, &readfds);
result = select(this->socketfd + 1, &readfds, NULL, NULL, &tv);
if (result > 0)
{
// cheating a bit here since the only thing in readfds will be this->socketfd
// normally you should check what of many file descriptors is set.
socklen_t len = sizeof(this->address);
int client_socket = accept(this->socketfd,
(struct sockaddr *) &this->address,
&tlen); // supply valid max length
if (client_socket == -1) {
throw "Error accepting client";
}
//do operation
}
else
{
// handle any failure except timeout here
}
}
}
I'm working on a c++ class that acts as a high-level wrapper around sockets in linux. While testing it, I purposely made the server's accept() call time out by having the client application sleep for a few seconds before calling connect().
However, after the server times out, the client application is still able to call connect() and send data without detecting an error. This is obviously a problem, because the server is not receiving the data, so the client should know the connection failed.
Here is my code. The server app calls Socket::accept_connection() and the client app sleeps and then calls Socket::connect_to().
// Accept a connection on the server side with a timeout
Socket *Socket::accept_connection(double timeout) {
Socket *new_connection = NULL;
socklen_t sin_size;
struct sockaddr_storage client_address; // Client's address
struct sockaddr_in client_port_address; // Client's port
char s[INET6_ADDRSTRLEN];
sin_size = sizeof client_address;
fd_set rfds;
struct timeval timeout_structure;
timeout_structure.tv_sec = (long)(timeout);
timeout_structure.tv_usec = int((timeout - timeout_structure.tv_sec) * 1e6);
struct timeval *timeout_ptr = NULL;
if(timeout > 0)
timeout_ptr = &timeout_structure;
// Loop until the timeout has been reached
while(true) {
FD_ZERO(&rfds);
FD_SET(socket_desc, &rfds);
if(select(socket_desc + 1, &rfds, NULL, NULL, timeout_ptr) > 0) {
int client_sock = accept(socket_desc, (struct sockaddr *)&client_address, &sin_size);
if(client_sock == -1) {
// Failed to connect
connected = false;
continue;
} else {
// Connected
inet_ntop(client_address.ss_family, get_in_addr((struct sockaddr *)&client_address), s, sizeof s);
getpeername(client_sock, (struct sockaddr*)&client_port_address, &sin_size);
int client_port = ntohs(client_port_address.sin_port);
// ...
}
} else {
// Timed out
connected = false;
std::cout << "accept() timed out\n";
break;
}
}
return new_connection;
}
// Connect to the given ip address and port
bool Socket::connect_to(std::string server_ip, int server_port, double timeout) {
connected = false;
// Create the socket and allocate memory for reading in data
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
struct timeval timeout_structure;
timeout_structure.tv_sec = (long)(timeout);
timeout_structure.tv_usec = int((timeout - timeout_structure.tv_sec) * 1e6);
struct timeval *timeout_ptr = NULL;
if(timeout > 0)
timeout_ptr = &timeout_structure;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(server_ip.c_str(), std::to_string(server_port).c_str(), &hints, &servinfo)) != 0) {
fprintf(stderr, "Socket error: connect_to, getaddrinfo: %s\n", gai_strerror(rv));
throw;
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((socket_desc = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("Socket error: connect_to, socket");
continue;
}
int flags = 0, error = 0, ret = 0;
fd_set rset, wset;
socklen_t len = sizeof(error);
//clear out descriptor sets for select
//add socket to the descriptor sets
FD_ZERO(&rset);
FD_SET(socket_desc, &rset);
wset = rset; //structure assignment ok
//set socket nonblocking flag
if((flags = fcntl(socket_desc, F_GETFL, 0)) < 0)
continue;
if(fcntl(socket_desc, F_SETFL, flags | O_NONBLOCK) < 0)
continue;
//initiate non-blocking connect
if(ret = connect(socket_desc, p->ai_addr, p->ai_addrlen) == -1) {
if (errno != EINPROGRESS) {
close(socket_desc);
perror("Socket error: connect_to, could not connect");
continue;
}
}
if(ret != 0) { // If connect did not succeed right away
// We are waiting for connect to complete now
if((ret = select(socket_desc + 1, NULL, &wset, NULL, timeout_ptr)) < 0)
return false;
if(ret == 0){ //we had a timeout
errno = ETIMEDOUT;
return false;
}
//we had a positive return so a descriptor is ready
if(FD_ISSET(socket_desc, &rset) || FD_ISSET(socket_desc, &wset)){
if(getsockopt(socket_desc, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error != 0)
return false;
} else
return false;
if(error){ //check if we had a socket error
errno = error;
return false;
}
}
//put socket back in blocking mode
if(fcntl(socket_desc, F_SETFL, flags) < 0)
return false;
break;
}
if(p == NULL) {
fprintf(stderr, "Socket error: connect_to, failed to connect\n");
socket_desc = 0;
return false;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
freeaddrinfo(servinfo); // all done with this structure
connected = true;
return connected;
}
This is normal, not a problem.
TCP maintains a listen backlog queue into which connections are placed that have been completed by the TCP stack but not yet accepted by the application.
TCP maintains a socket receive buffer per socket into which data is placed that has arrived from the peer and not yet been read by the application.
the client should know the connection failed.
It didn't fail. The server can accept it and read the data.
I am working on a client-server application where I have two different ports, one (principal) for us send and receive messages or any other order, and another one to send and receive screenshots of the server to the client. From client to server notice to start us send'll catch and showing in a new window ... works fine but if I close the window and open it again then and I can not connect to that port (bind fails me).
MY question is how do I clean or completely release the port I use for screenshots without affecting the main port, that is, when you close the window to release the port as if I had never used and advise the client to do the same.
Here I leave the code:
Server:
int serviceCapture(int port)
{
int error;
WSAData wsaDataER;
error = WSAStartup(MAKEWORD(2, 2), &wsaDataER);
if (error == SOCKET_ERROR)
{
return 1;
}
// ShowMessage ("Server: WinSocket Started Correctly!\n");
sock_ER = socket(AF_INET, SOCK_STREAM, 0);
if (sock_ER == SOCKET_ERROR)
{
return 2;
}
struct sockaddr_in escritorioRem; // New! Our network socket structure
escritorioRem.sin_family = AF_INET; // Always have ti as this for internet
escritorioRem.sin_port = htons(puerto); // Dont forget the byte ordering
escritorioRem.sin_addr.s_addr = INADDR_ANY;internet
if(!enviandoCapturas){
error = bind(sock_ER, (sockaddr*)&escritorioRem, sizeof(escritorioRem)); // Attempt to bind the socket
if (error == SOCKET_ERROR)
{
return 3 ;
}
}
error = listen(sock_ER, 1); // Listen for connections
if (error == SOCKET_ERROR)
{
return 4;
}
// }
//ShowMessage ( "Server: Waiting for a client to connect ...\n"); // Just to keep us up to date - ish
int len= sizeof (struct sockaddr);
sock_ER=accept(sock_ER,(sockaddr*)&escritorioRem, &len);
//
//do{
if( sock_ER<0){
return 5;
}
sendingCaps=true;
startSendCaps();
return 0;
}
Client:
int client(string serv, int puerto)
{
int error;
WSAData wsaData;
error = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (error == SOCKET_ERROR)
{
return 1;
}
// ShowMessage( "Client: WinSocket Loaded.\n");
if (sock == SOCKET_ERROR)
{
return 2;
}
// ShowMessage( "Client: Socket Opened Successfully!\n");
const char *server_name = serv.c_str(); // The server name we will connect to
struct hostent *host_entry; // Translates into something the computer can understand
host_entry = gethostbyname(server_name); // Gather out information
if (host_entry == NULL)
{
return 3;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons((unsigned short) puerto);
server.sin_addr.s_addr = *(unsigned long*) host_entry->h_addr;
if(connect(ventanaCliente->sock, (sockaddr*)&server, sizeof(struct sockaddr))<0){
return 4;
}
receivingCaps=true;
strartReceiveCaps();
return 0;
}
back again (sorry)
I've created a socket C++ application, but it isn't working properly.
This is my first code:
void Network::Start()
{
this->socket = Env::GetSocket();
SOCKADDR_IN sInformation;
sInformation.sin_family = AF_INET;
sInformation.sin_addr.s_addr = INADDR_ANY;
sInformation.sin_port = htons(30000);
bind(this->socket, (SOCKADDR*) (&sInformation), sizeof(sInformation));
listen(this->socket, 10);
while (true)
{
this->DO();
}
}
And the DO function:
void Network::DO()
{
SOCKET s = SOCKET_ERROR;
sockaddr_in sock_addr;
accept(s, (sockaddr*) &sock_addr, NULL);
if (INVALID_SOCKET == s)
{
return;
}
else
{
cout << "Received connection from " << inet_ntoa(sock_addr.sin_addr);
}
}
What happens, always (even if I connect) the value s is INVALID_SOCKET. I connect via a .SWF but it doesn't accept my connection. What am I doing wrong?
You are not doing adequate error handling, and you are not using accept() correctly. Try this:
void Network::Start()
{
this->socket = Env::GetSocket();
if (this->socket == INVALID_SOCKET)
{
// error
return;
}
SOCKADDR_IN sInformation = {0};
sInformation.sin_family = AF_INET;
sInformation.sin_addr.s_addr = INADDR_ANY;
sInformation.sin_port = htons(30000);
if (bind(this->socket, (SOCKADDR*) &sInformation, sizeof(sInformation)) != 0)
{
// error
return;
}
if (listen(this->socket, 10) != 0)
{
// error
return;
}
while (true)
{
this->DO();
}
}
void Network::DO()
{
SOCKADDR_IN sock_addr = {0};
socklen_t sock_addr_len = sizeof(sock_addr);
SOCKET s = accept(this->socket, (SOCKADDR*) &sock_addr, &sock_addr_len);
if (INVALID_SOCKET == s)
{
return;
}
cout << "Received connection from " << inet_ntoa(sock_addr.sin_addr);
// use s as needed. Don't forget to call close(s) or closesocket(s)
// when finished, depending on your platform...
}
accept takes the listening socket as a parameter, and returns the newly connected socket;
socklen_t length = sizeof(sockaddr_in);
s = accept(this->socket, (sockaddr*) &sock_addr, &length);
EDIT: Just tested the program, with the socket created with AF_INET, SOCK_STREAM and sInformation cleared out;
bzero((char *) &sInformation, sizeof(sInformation));
...it seems to be running well on MacOS X and linux.