Clearing the buffer-Winsock - c++

Here is my code for the client program I have made in C++ using winsock in Windows.
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include<sstream>
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFLEN 512
#pragma comment(lib,"WS2_32.lib");
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
int main()
{
WSAData wsadata;
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
char *sendbuf = "1,2,3,4!!";
char recvbuf[512];
iResult=WSAStartup(MAKEWORD(2,2),&wsadata);
if(iResult!=0)
{
std::cout<<"WSAStartup failed"<<iResult<<std::endl;
getchar();
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
char arr[20]="localhost";
iResult = getaddrinfo(arr, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
{
std::cout<<"getaddrinfo failed: "<<iResult;
getchar();
WSACleanup();
return 1;
}
SOCKET ConnectSocket = INVALID_SOCKET;
ptr=result;
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
std::cout<<"Error at socket(): "<<WSAGetLastError();
getchar();
freeaddrinfo(result);
WSACleanup();
return 1;
}
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET)
{
std::cout<<"Unable to connect to server!"<<std::endl;
getchar();
WSACleanup();
return 1;
}
for(;;)
{
int i=15;
int x=12;
int z=1;
iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
std::cout<<"Recieved data: "<<recvbuf<<std::endl;
}
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
std::cout<<"shutdown failed: "<<WSAGetLastError();
getchar();
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
if (iResult == 0)
std::cout<<"Connection closed\n";
else
std::cout<<"recv of client failed: "<<WSAGetLastError();
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
std::cout<<"shutdown failed: "<<WSAGetLastError();
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
closesocket(ConnectSocket);
WSACleanup();
getchar();
return 0;
}
The information that I am receiving is fine. The only problem is that I want to clear the buffer every time I receive some data.
The output of the current code if I send a,b,c,d is something like
a,b,c,d
aa,bb,cc,dd
aaa,bbb,ccc,ddd
While I want my output to be a,b,c,d as it keeps receiving this information again and again. How to do this?

This code in what you provided looks like an infinite loop:
for(;;)
{
int i=15;
int x=12;
int z=1;
iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
std::cout<<"Recieved data: "<<recvbuf<<std::endl;
}
On top of that, it outputs recvbuf as if it were a string, but there is no guarantee that it will be \0 terminated, and will likely lead to undefined behavior if you actually read the full DEFAULT_BUFLEN bytes of data. I would suggest a string conversion before printing. But before that, the return value of recv should be checked.
iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFLEN, 0);
if (iResult <= 0) break;
std::cout<<"Received data: " <<std::string(recvbuf,iResult)<<std::endl;

Related

How to use select() to set a timer for sockets?

I'm currently using Winsock2 to be able to test a connection to multiple local telnet servers, but if the server connection fails, the default Winsock client takes forever to timeout.
I've seen from other posts that select() can set a timeout for the connection part, and that setsockopt() with timeval can timeout the receiving portion of the code, but I have no idea how to implement either. Pieces of code that I've copy/pasted from other answers always seem to fail for me.
How would I use both of these functions in the default client code? Or, if it isn't possible to use those functions in the default client code, can someone give me some pointers on how to use those functions correctly?
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctime>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "23"
int __cdecl main(int argc, char** argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo* result = NULL,
* ptr = NULL,
hints;
const char* sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
/*
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,
sizeof(timeout)) < 0) {
printf("setsockopt failed\n");
}
*/
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
select() can set a timeout for the connection part.
Yes, but only if you put the socket into non-blocking mode before calling connect(), so that connect() exits immediately and then the code can use select() to wait for the socket to report when the connect operation has finished. But the code shown is not doing that.
setsockopt() with timeval can timeout the receiving portion of the code
Yes, though select() can also be used to timeout a read operation, as well. Simply call select() first, and then call recv() only if select() reports that the socket is readable (has pending data to read).
Try something like this:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctime>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "23"
int __cdecl main(int argc, char** argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
const char* sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// put the socket into non-blocking mode just for connect()
int iMode = 1;
iResult = ioctlsocket(ConnectSocket, FIONBIO, &iMode);
if (iResult == SOCKET_ERROR)
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
// wait for the connect to finish
fd_set fds;
FD_ZERO(&fds);
FD_SET(ConnectSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
iResult = select(0, NULL, &fds, NULL, &timeout);
if (iResult <= 0) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
}
// put the socket back into blocking mode
iMode = 0;
iResult = ioctlsocket(ConnectSocket, FIONBIO, &iMode);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
// set a read timeout
if (setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) == SOCKET_ERROR) {
printf("setsockopt failed\n");
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
/*
fd_set fds;
FD_ZERO(&fds);
FD_SET(ConnectSocket, &fds);
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
iResult = select(0, &fds, NULL, NULL, &timeout);
if (iResult <= 0) {
if (iResult == SOCKET_ERROR)
printf("select failed with error: %d\n", WSAGetLastError());
else
printf("select timed out\n");
break;
}
*/
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else if (WSAGetLastError() == WSAETIMEDOUT)
printf("recv timed out\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}

Winsock2, client-server communication - send/recv in turns

I want to write a client/server application, in which client and server can exchange messages.
Client site communication:
send
recv
send
recv
Server site communication:
recv
send
recv
send
However, I have a problem, because only one message is send/recv. After that, the socket is closed and further messages are not being sent. Whats wrong and how to fix this? Thank you.
Server code:
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_PORT "27501"
#define SIZE 1024
int SendAllToClient(SOCKET ClientSocket, char *buffer)
{
int iSendResult;
int total = 0, len = 1024;
int bytesleft = 1024;
while( total < len )
{
iSendResult = send( ClientSocket, buffer, 1024, NULL);
if (iSendResult == SOCKET_ERROR)
{
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
total += iSendResult;
bytesleft -= iSendResult;
}
printf("Bytes sent: %d\n", iSendResult);
return total<len?- 1: 1;
}
char *ReadFromClient(SOCKET ConnectSocket)
{
int iResult;
char *buffer = new char[1024];
memset(buffer, 0, 1024);
do
{
iResult = recv(ConnectSocket, buffer, 1024, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
}
while( iResult > 0 );
return buffer;
}
int main(int argc , char *argv[])
{
WSADATA wsaData;
char *buffer;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int sessionID;
int iResult;
// Datagram d1,d2,d3;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 )
{
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
printf("socket failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR)
{
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
printf("Server is listening on localhost:%s ...\n", DEFAULT_PORT);
// Accept a client socket
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
ClientSocket = accept(ListenSocket, (SOCKADDR*)&addr, &addrlen);
if (ClientSocket == INVALID_SOCKET)
{
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
char *ip = inet_ntoa(addr.sin_addr);
int port = addr.sin_port;
printf("\nClient %s:%d connected to server\n", ip, port);
// No longer need server socket
closesocket(ListenSocket);
// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
//read
buffer = ReadFromClient(ClientSocket);
printf("FROM CLIENT: %s\n", buffer);
//send
memset(buffer, 0, 1024);
memcpy(buffer, "Hi client, how are you?", strlen("Hi client, how are you?"));
SendAllToClient(ClientSocket, buffer);
//read
//send
// cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
Client code:
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_PORT "27501"
#define SIZE 1024
int SendAllToServer(SOCKET ServerSocket, char *buffer)
{
int iSendResult;
int total = 0, len = 1024;
int bytesleft = 1024;
while( total < len )
{
iSendResult = send( ServerSocket, buffer, 1024, NULL);
if (iSendResult == SOCKET_ERROR)
{
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ServerSocket);
WSACleanup();
return 1;
}
total += iSendResult;
bytesleft -= iSendResult;
}
printf("Bytes sent: %d\n", iSendResult);
return total<len?- 1: 1;
}
char *ReadFromServer(SOCKET ConnectSocket)
{
int iResult;
char *buffer = new char[1024];
memset(buffer, 0, 1024);
do {
iResult = recv(ConnectSocket, buffer, 1024, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
return buffer;
}
int main(int argc , char *argv[])
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char* buffer;
int sessionID;
int iResult;
// Datagram d1,d2;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
//send
buffer = new char[1024];
memset(buffer, 0, 1024);
memcpy(buffer, "Hi server", strlen("Hi server"));
SendAllToServer(ConnectSocket, buffer);
//read
memset(buffer, 0, 1024);
buffer = ReadFromServer(ConnectSocket);
printf("FROM SERVER: %s\n", buffer);
//send
//read
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
EDIT
Server
#include "data_types.h"
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
#define SIZE 1024
int SendAllToClient(SOCKET ClientSocket)
{
char *buffer = new char[SIZE];
int iSendResult;
memset(buffer, 0, SIZE);
int total = 0, len = SIZE;
int bytesleft = SIZE;
while( total < len )
{
iSendResult = send( ClientSocket, buffer + total, bytesleft, NULL);
if (iSendResult == SOCKET_ERROR)
{
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
total += iSendResult;
bytesleft -= iSendResult;
}
printf("Bytes sent: %d\n", iSendResult);
delete buffer;
return total<len?- 1: 1;
}
char* ReadFromClient(SOCKET ClientSocket)
{
std::string data = "";
char *all = NULL;
char buffer[1];
int total = 0, len = SIZE;
int bytesleft = SIZE;
int iResult;
memset(buffer, 0, 1);
while(total < len)
{
if ((iResult = recv(ClientSocket, buffer, 1, 0)) == 0)
{
if (errno != 0)
{
// cleanup
closesocket(ClientSocket);
WSACleanup();
exit(1);
}
}
data = data + std::string(buffer);
total += iResult;
bytesleft -= iResult;
memset(buffer, 0, 1);
}
all = new char[data.length() + 1];
strcpy(all, data.c_str());
return all;
}
int main(int argc , char *argv[])
{
WSADATA wsaData;
char *buffer;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int sessionID;
int iResult;
// Datagram d1,d2,d3;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 )
{
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
printf("socket failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR)
{
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
printf("Server is listening on localhost:%s ...\n", DEFAULT_PORT);
// Accept a client socket
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
ClientSocket = accept(ListenSocket, (SOCKADDR*)&addr, &addrlen);
if (ClientSocket == INVALID_SOCKET)
{
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
char *ip = inet_ntoa(addr.sin_addr);
int port = addr.sin_port;
printf("\nClient %s:%d connected to server\n", ip, port);
// No longer need server socket
closesocket(ListenSocket);
// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
//read
buffer = new char[1024];
memset(buffer, 0, 1024);
buffer = ReadFromClient(ClientSocket);
printf("FROM CLIENT: %s\n", buffer);
//send
memset(buffer, 0, 1024);
memcpy(buffer, "Hi client, how are you?", strlen("Hi client, how are you?"));
// Send an initial buffer
iResult = send( ClientSocket, buffer, (int)strlen(buffer), 0 );
if (iResult == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
//read
//send
// cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
Client
#include "data_types.h"
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
#define SIZE 1024
int SendAllToServer(SOCKET ClientSocket)
{
char *buffer = new char[SIZE];
memset(buffer, 0, SIZE);
int total = 0, len = SIZE;
int bytesleft = SIZE, iSendResult;
while( total < len )
{
iSendResult = send( ClientSocket, buffer + total, bytesleft, NULL);
if (iSendResult == SOCKET_ERROR)
{
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
total += iSendResult;
bytesleft -= iSendResult;
}
printf("Bytes sent: %d\n", iSendResult);
delete buffer;
return total<len?- 1: 1;
}
char *ReadFromServer(SOCKET ClientSocket)
{
std::string data = "";
char *all = NULL;
char buffer[1];
int total = 0, len = SIZE;
int bytesleft = SIZE;
int iResult;
memset(buffer, 0, 1);
while(total < len)
{
if ((iResult = recv(ClientSocket, buffer, 1, 0)) == 0)
{
if (errno != 0)
{
// cleanup
closesocket(ClientSocket);
WSACleanup();
exit(1);
}
}
data = data + std::string(buffer);
total += iResult;
bytesleft -= iResult;
memset(buffer, 0, 1);
}
all = new char[data.length() + 1];
strcpy(all, data.c_str());
return all;
}
int main(int argc , char *argv[])
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char* buffer;
int sessionID;
int iResult;
// Datagram d1,d2;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
//send
buffer = new char[1024];
memset(buffer, 0, 1024);
memcpy(buffer, "Hi server, how are you?", strlen("Hi server, how are you?"));
// Send an initial buffer
iResult = send( ConnectSocket, buffer, (int)strlen(buffer), 0 );
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
//read
memset(buffer, 0, 1024);
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, buffer, 1024, 0);
if ( iResult > 0 )
wprintf(L"Bytes received: %d\n", iResult);
else if ( iResult == 0 )
wprintf(L"Connection closed\n");
else
wprintf(L"recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
printf("FROM SERVER: %s\n", buffer);
//send
//read
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
First issue:
iSendResult = send( ClientSocket, buffer, 1024, NULL);
That 1024 should be bytesleft. If you've already read 512 bytes, you don't want to read more than another 512.
That buffer should be buffer + total. If you've already sent 512 bytes, you don't want to send the same 512 bytes again, you want to send the other 512 bytes.
Second issue:
Your ReadFromServer function is just completely broken and doesn't follow the right logic. It only returns on a fatal error and doesn't even try to read exactly 1,024 bytes. It just reads up to 1,024 bytes and then, no matter how many bytes it actually read, tries to read 1,024 bytes again -- and at the same address overwriting whatever part of the message it already read!
It should work just like the send function, first trying to receive 1,024 bytes and looping if it receives less than that until it has either received exactly 1,024 bytes or gotten a fatal error.
Third issue:
buffer = ReadFromServer(ConnectSocket);
printf("FROM SERVER: %s\n", buffer);
Don't do this. Suppose the server is malicious and sent you 1,024 bytes that are not a legal C-style string. Passing that to printf through %s could cause the client to crash or misbehave. Always treat data received from the network as untrusted and potentially hostile. Though your code will work without fixing this, one day doing this will bite you in some awful way and it's not a good habit to get into.
You should also delete[] the buffer when you're done with it. But why would you return a raw pointer anyway? You could return a std::string, a std::vector, or many other much better mechanisms that avoid the risk of leaks and make copies safe.
In fact you are closing the listen socket, so once there is an accepted connection it won't accept any more:
ClientSocket = accept(ListenSocket, (SOCKADDR*)&addr, &addrlen);
if (ClientSocket == INVALID_SOCKET)
{
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
char *ip = inet_ntoa(addr.sin_addr);
int port = addr.sin_port;
printf("\nClient %s:%d connected to server\n", ip, port);
// No longer need server socket
closesocket(ListenSocket);
Closing the listener prevents further connections.
Also, you are closing the client socket before handling it:
// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
//read
buffer = new char[1024];
memset(buffer, 0, 1024);
buffer = ReadFromClient(ClientSocket);
printf("FROM CLIENT: %s\n", buffer);
//send
memset(buffer, 0, 1024);
memcpy(buffer, "Hi client, how are you?", strlen("Hi client, how are you?"));
// Send an initial buffer
iResult = send( ClientSocket, buffer, (int)strlen(buffer), 0 );
If you want to send and receive several times, you should read/write in a loop. You are doing that only once (and doing it incorrectly): so only one message as you describe in your question.

WTSEnumerateProcesses with socket and data struct

I'm new with C++ Windows API and I've got few questions about using the WTSEnumerateProcesses() API.
My target: use WTSEnumerateProcesses(), take only the process list, put it in any kind of "list" or struct, convert the widechar to ANSI, and send it to a socket using Winsock.
That's my code below:
Winsock:
int connect(char buffer[])
{
PCSTR ip = "localhost";
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
const char *sendbuf =buffer;
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(ip, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
}
while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
and the WTSEnumerateProcesses():
void GetProcesslist()
{
vector<LPWSTR> v; // no need to prepend std:: any more
LPWSTR pProcessName;
WTS_PROCESS_INFO* pWPIs = NULL;
DWORD dwProcCount = 0;
if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, NULL, 1, &pWPIs, &dwProcCount))
{
//Go through all processes retrieved
for (DWORD i = 0; i < dwProcCount; i++)
{
pProcessName = pWPIs[i].pProcessName;
v[i] = pProcessName;
//contains(pProcessName);
// process file name only, no path!
//data = pProcessName;
std::wcout << pProcessName << endl;
//pWPIs[i].ProcessId = process ID
//pWPIs[i].SessionId = session ID, if you need to limit it to the logged in user processes
//pWPIs[i].pUserSid = user SID that started the process
}
}
//Free memory
if (pWPIs)
{
WTSFreeMemory(pWPIs);
pWPIs = NULL;
}
}
Can you please help me to understand how I can take the process list only, push it to any struct (like a list?) and send it correctly over the TCP socket, that is waiting to get a const char[] and not wide characters?
You are not using std::vector correctly in your GetProcesslist(). You are trying to access elements you have not allocated any memory for. And worse, you are storing pointers to data that you free before GetProcesslist() exits, leaving the vector containing dangling pointers (were you to access that vector outside of GetProcesslist(), which you are not doing yet).
Try something more like this:
std::vector<std::wstring> GetProcesslist()
{
std::vector<std::wstring> v;
WTS_PROCESS_INFO* pWPIs = NULL;
DWORD dwProcCount = 0;
if (WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, NULL, 1, &pWPIs, &dwProcCount))
{
//Go through all processes retrieved
for (DWORD i = 0; i < dwProcCount; ++i)
{
LPWSTR pProcessName = pWPIs[i].pProcessName;
v.push_back(pProcessName);
// process file name only, no path!
//data = pProcessName;
std::wcout << pProcessName << endl;
//pWPIs[i].ProcessId = process ID
//pWPIs[i].SessionId = session ID, if you need to limit it to the logged in user processes
//pWPIs[i].pUserSid = user SID that started the process
}
//Free memory
WTSFreeMemory(pWPIs);
}
return v;
}
Then, I would suggest sending the data over the socket like this:
int connect(const char buffer[], size_t buffersize)
{
PCSTR ip = "localhost";
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
const char *sendbuf = buffer;
char recvbuf[DEFAULT_BUFLEN];
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(ip, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
while (buffersize > 0) {
iResult = send(ConnectSocket, sendbuf, (int)buffersize, 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
sendbuf += iResult;
buffersize -= iResult;
}
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, sizeof(recvbuf), 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
}
while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
std::vector<std::wstring> procs = GetProcesslist();
std::vector<char> buffer;
size_t size = sizeof(uint32_t);
for(const std::wstring &name : procs) {
size += (sizeof(uint32_t) + WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name.size(), NULL, 0, NULL, NULL));
}
buffer.resize(size);
char *ptr = buffer.data();
*reinterpret_cast<uint32_t*>(ptr) = htonl(procs.size());
ptr += sizeof(uint32_t);
for(const std::wstring &name : procs) {
int len = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name.size(), NULL, 0, NULL, NULL));
*reinterpret_cast<uint32_t*>(ptr) = htonl(len);
ptr += sizeof(uint32_t);
if (len > 0) {
ptr += WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name.size(), ptr, len, NULL, NULL));
}
}
connect(buffer.data(), buffer.size());
Or, if you absolutely cannot change the signature of connect() and must pass it a null-terminated C string, then try this:
int connect(const char buffer[])
{
PCSTR ip = "localhost";
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
const char *sendbuf = buffer;
sendbuflen = strlen(buffer);
char recvbuf[DEFAULT_BUFLEN];
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(ip, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
while (sendbuflen > 0) {
iResult = send(ConnectSocket, sendbuf, sendbuflen, 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
sendbuf += iResult;
sendbuflen -= iResult;
}
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, sizeof(recvbuf), 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
}
while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
std::vector<std::wstring> procs = GetProcesslist();
std::ostringstream oss;
oss << procs.size() << "\x1";
for(const std::wstring &name : procs) {
int len = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name.size(), NULL, 0, NULL, NULL);
if (len > 0) {
std::string s;
s.resize(len);
WideCharToMultiByte(CP_UTF8, 0, name.c_str(), name.size(), &s[0], len, NULL, NULL);
oss << s;
}
oss << "\x1";
}
connect(oss.str().c_str());

getaddrinfo Error code 11001

i am completely new to sockets in c++. So i already checked a few topics here, but i am not able to get it going. Please also don't judge about the code, it's mostly try and error for myself. So what i am basically try to do is to save the response from this website:
http://automatica.ais.mw.tum.de/dbConnectKoordinator/index.php?msg=0,5,1
Further, i need to change the last numbers, then the answer will be different, for example
http://automatica.ais.mw.tum.de/dbConnectKoordinator/index.php?msg=1,1,5,1
I think, that my code already works, i tried www.example.com and i can save the answer and show it in the console. Also for other website i dont get an error code. But when i try websites like the one above it is not working and i get the errorcode 11001 during the function getaddrinfo. Same for the website "eu.battle.net/api/d3/profile/ArTzT-2294/hero/280061" for example.
So please, if somebody could help me out on this one, i would be very thankful.
Here is my code (as i already told, its a complete mess. for me it is only important to save the answer of the website, nothing else)
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
#include <stdio.h>
#include <WS2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
#define DEFAULT_PORT "80"
#define DEFAULT_BUFLEN 512
int __cdecl main(int argc, char** argv)
{
WSADATA wsaData;
int iResult;
int iRetval;
DWORD dwRetval;
int i = 1;
char ipstringbuffer[46];
DWORD ipbufferlength = 46;
int recvbuflen = DEFAULT_BUFLEN;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
//argv[1] = "www.example.com";
//Winsock initialisieren
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
cout << "WSAStartup failed: " << iResult;
return 1;
}//if
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
struct sockaddr_in *sockaddr_ipv4;
struct sockaddr_in6 *sockaddr_ipv6;
LPSOCKADDR sockaddr_ip;
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
//Resolve the server address and port
iResult = getaddrinfo("www.example.com", DEFAULT_PORT, &hints, &result);
if (iResult != 0)
{
cout << "getaddrinfo failed: " << iResult;
WSACleanup();
//cin.get();
return 1;
}//if
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next)
{
switch (ptr->ai_family)
{
case AF_UNSPEC:
break;
case AF_INET:
sockaddr_ipv4 = (struct sockaddr_in *)
ptr->ai_addr;
break;
case AF_INET6:
sockaddr_ipv6 = (struct sockaddr_in6 *)
ptr->ai_addr;
break;
case AF_NETBIOS:
break;
default:
break;
}
SOCKET ConnectSocket = INVALID_SOCKET;
//Attempt to connect to the first address returned by
//the call to getaddrinfo
ptr=result;
//Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
cout << "Error at socket(): WSAGetLastError()";
freeaddrinfo(result);
WSACleanup();
return 1;
}//if
//Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
}//if
if (ConnectSocket == INVALID_SOCKET)
{
WSACleanup();
return 1;
}//if
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int) strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR)
{
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection for sending since no more data will be sent
// the client can still use the ConnectSocket for receiving data
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive data until the server closes the connection
do
{
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0){
printf("Bytes received: %d\n", iResult);
cout << "Alles: \n" << recvbuf;
cout << "\n\nNur eins: \n" << recvbuf[0];
}
else if (iResult == 0){
printf("Connection closed\n");
}
else {
printf("recv failed: %d\n", WSAGetLastError());
}
} while (iResult > 0);
// shutdown the send half of the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ConnectSocket);
WSACleanup();
cin.get();
return 0;
}
I also tried this with the cpp-netlib but i also get an error: "lobboost_system-vc100-mt-gd-1_55.lib" can not be opened
How can I fetch data from a website inside a C++ program
Thank you very much!

error C2664: 'errno_t strcpy_s(char *,rsize_t,const char *)' : cannot convert parameter 2 from 'char [512]' to 'rsize_t' [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Code:
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iostream>
#include <string>
// link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFFER_LENGTH 512
class Client {
public:
Client(char* servername)
{
szServerName = servername;
ConnectSocket = INVALID_SOCKET;
}
bool Start() {
WSADATA wsaData;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0)
{
printf("WSAStartup failed: %d\n", iResult);
return false;
}
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(szServerName, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
{
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return false;
}
ptr = result;
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
printf("Error at socket(): %d\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return false;
}
// Connect to server
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET)
{
printf("Unable to connect to server!\n");
WSACleanup();
return false;
}
return true;
};
// Free the resouces
void Stop() {
int iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
printf("shutdown failed: %d\n", WSAGetLastError());
}
closesocket(ConnectSocket);
WSACleanup();
};
// Send message to server
bool Send(char* szMsg)
{
int iResult = send(ConnectSocket, szMsg, strlen(szMsg), 0);
if (iResult == SOCKET_ERROR)
{
printf("send failed: %d\n", WSAGetLastError());
Stop();
return false;
}
return true;
};
// Receive message from server
bool Recv()
{
char recvbuf[DEFAULT_BUFFER_LENGTH];
int iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
if (iResult > 0)
{
char msg[DEFAULT_BUFFER_LENGTH];
memset(&msg, 0, sizeof(msg));
strcpy_s(msg, recvbuf, iResult);
printf("Received: %s\n", msg);
return true;
}
return false;
}
private:
char* szServerName;
SOCKET ConnectSocket;
};
int main(int argc, CHAR* argv[])
{
std::string msg;
Client client("127.0.0.1");
if (!client.Start())
return 1;
while(true)
{
std::cout << "Send: ";
std::getline(std::cin, msg);
// Close the connection when user enter "close"
if (msg.compare("close") == 0)
{
break;
}
client.Send((char*)msg.c_str());
client.Recv();
}
client.Stop();
getchar();
return 0;
}
and
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
// link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFFER_LENGTH 512
int main() {
WSADATA wsaData;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0)
{
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
struct addrinfo *result = NULL,
hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; // Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned
hints.ai_socktype = SOCK_STREAM; // Requests the socket type to be a stream socket for the TCP protocol
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
{
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
SOCKET ListenSocket = INVALID_SOCKET;
// Create a SOCKET for the server to listen for client connections
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
printf("Error at socket(): %d\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
printf("bind failed: %d", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
// To listen on a socket
if ( listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
printf("listen failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
SOCKET ClientSocket;
ClientSocket = INVALID_SOCKET;
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET)
{
printf("accept failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
char recvbuf[DEFAULT_BUFFER_LENGTH];
int iSendResult;
// reveice until the client shutdown the connection
do {
iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
if (iResult > 0)
{
char msg[DEFAULT_BUFFER_LENGTH];
memset(&msg, 0, sizeof(msg));
strcpy_s(msg, recvbuf, iResult);
printf("Received: %s\n", msg);
iSendResult = send(ClientSocket, recvbuf, iResult, 0);
if (iSendResult == SOCKET_ERROR)
{
printf("send failed: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf("Bytes sent: %ld\n", iSendResult);
}
else if (iResult == 0)
printf("Connection closed\n");
else
{
printf("recv failed: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
//return 1;
}
} while (iResult > 0);
// Free the resouces
closesocket(ListenSocket);
WSACleanup();
getchar();
return 0;
}
Errors:
error C2664: 'errno_t strcpy_s(char *,rsize_t,const char *)' : cannot
convert parameter 2 from 'char [512]' to 'rsize_t'
error C2664: 'errno_t strcpy_s(char *,rsize_t,const char *)' : cannot
convert parameter 2 from 'char [512]' to 'rsize_t'
IntelliSense: no instance of overloaded function "strcpy_s" matches
the argument list
argument types are: (char [512], char [512], int)
I have been trying to fix this problem. Please help.
New code:
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
// link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFFER_LENGTH 128
int main() {
WSADATA wsaData;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0)
{
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
struct addrinfo *result = NULL,
hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; // Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned
hints.ai_socktype = SOCK_STREAM; // Requests the socket type to be a stream socket for the TCP protocol
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
{
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
SOCKET ListenSocket = INVALID_SOCKET;
// Create a SOCKET for the server to listen for client connections
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
printf("Error at socket(): %d\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
printf("bind failed: %d", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
// To listen on a socket
if ( listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
printf("listen failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
SOCKET ClientSocket;
ClientSocket = INVALID_SOCKET;
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET)
{
printf("accept failed: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
char recvbuf[DEFAULT_BUFFER_LENGTH];
int iSendResult;
// reveice until the client shutdown the connection
do {
iResult = recv(ClientSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
if (iResult > 0)
{
char msg[DEFAULT_BUFFER_LENGTH];
memset(&msg, 0, sizeof(msg));
strcpy_s(msg, iResult, recvbuf);
printf("Received: %s\n", msg);
iSendResult = send(ClientSocket, recvbuf, iResult, 0);
if (iSendResult == SOCKET_ERROR)
{
printf("send failed: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf("Bytes sent: %ld\n", iSendResult);
}
else if (iResult == 0)
printf("Connection closed\n");
else
{
printf("recv failed: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
//return 1;
}
} while (iResult > 0);
// Free the resouces
closesocket(ListenSocket);
WSACleanup();
getchar();
return 0;
}
New error:
http://i.stack.imgur.com/55IUF.png
You have the parameters in the wrong order.
errno_t strcpy_s(char *dest, rsize_t size, const char *src);
You put the src in the size param and the size in the src param.