This socket library is the library that was used with
PCL++.
It is very simple compared to most ocket libraries that are available. This is for windows. Before you start using sockets in your program you must put this code. You must link your program to ws2_32.dll, when ocmpiling with bloodshed dev link to lib/libws2_32.a instead.
Before your first connecttosocket put.
Code:
int ws2result;
ws2result = startws2();
if(ws2result != 0) {
//printf("WSAStartup failed: %d\n", ws2result);
return ws2result;
}
Put this in a file called socket.h and include it in your program.
Code:
#include <winsock2.h>
SOCKET ConnectSocket = INVALID_SOCKET;
char recvbuf[DEFAULT_BUFLEN];
using namespace std;
// Initialize Winsock
int startws2(){
WSADATA wsaData;
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0) {
/*printf("WSAStartup failed: %d\n", iResult);*/
return iResult;
}
else{
return 0;
}
}
int connecttosocket(string host, string portno){
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;
#define DEFAULT_PORT "6112"
iResult = getaddrinfo(host.c_str(), portno.c_str(), &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
ptr=result;
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
// 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 1;
}
}
char *readRawPacket(){
int recvbuflen = DEFAULT_BUFLEN
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if( iResult > 0 ){
return recvbuf;
}
else if ( iResult == 0 ){
//printf("Connection closed\n");
return "0";
}
else
printf("recv failed: %d\n", WSAGetLastError());
return "-1";
} while( iResult > 0 );
return "1";
}
int sendRawPacket(string sendbuf) {
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf.c_str(), (int)strlen(sendbuf.c_str()) + 1, 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
}