Send and Receive Live data using UDP Socket - c++

I am practicing socket programming. Here is my server code.
Server.cpp
/* UDP Server Sample program*/
#include <Windows.h>
#include <iostream>
#include <winsock.h>
using namespace std;
int main()
{
// Local Variable definitions
cout << "\t\t------- UDP Server---" << endl;
cout << endl;
WSADATA WinSockData;
int iWsaStartup;
int iWsaCleanup;
SOCKET UDPSocketServer;
struct sockaddr_in UDPClient;
char Buffer[512];
int iBufferLen = strlen(Buffer) + 1;
int iBind;
int iReceiveFrom;
int iUDPClientLen = sizeof(UDPClient);
int iCloseSocket;
// STEP-1 Initialization of Winsock
iWsaStartup = WSAStartup(MAKEWORD(2, 2), &WinSockData);
if (iWsaStartup != 0)
{
cout << "WSAStartUp Fun Failed" << endl;
}
cout << "WSAStartUp Success" << endl;
//STEP-2 Fill the UDPClient(SOCKET ADDRESS) Structure
UDPClient.sin_family = AF_INET;
UDPClient.sin_addr.s_addr = inet_addr("169.254.131.8");
UDPClient.sin_port = htons(8001);
// STEP-3 Socket Creation
UDPSocketServer = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (UDPSocketServer == INVALID_SOCKET)
{
cout << "Socket Creation Failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "Socket Creation Success" << endl;
// STEP-4 bind the server
iBind = bind(
UDPSocketServer,
(SOCKADDR*)&UDPClient,
sizeof(UDPClient));
if (iBind == SOCKET_ERROR)
{
cout << "Binding Failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "Binding Success" << endl;
//STEP-5 RecvFrom Fun from receive data from client
while (1)
{
iReceiveFrom = recvfrom(
UDPSocketServer,
Buffer,
iBufferLen,
MSG_PEEK,
(SOCKADDR*)&UDPClient,
&iUDPClientLen);
if (iReceiveFrom == SOCKET_ERROR)
{
cout << "Receiving failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "Receiving Success" << endl;
cout << "Receive Data -> " << Buffer << endl;
}
//STEP-6 CloseSocket Function
iCloseSocket = closesocket(UDPSocketServer);
if (iCloseSocket == SOCKET_ERROR)
{
cout << "Socket Closing failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "Socket CLosing Success" << endl;
//STEP-7 WSACLeanUp Fun for Terminating the use of DLL
iWsaCleanup = WSACleanup();
if (iWsaCleanup == SOCKET_ERROR)
{
cout << "WSA CleanUp failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "WSA CleanUp Success" << endl;
system("PAUSE");
return 0;
}
and this is client code...
client.cpp
/*All right reserved to awinsyspro.com 2019*/
/* UDP Server Sample program*/
#include <Windows.h>
#include <winsock.h>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "\t\t------UDP Client------" << endl;
cout << endl;
// Local Variable
WSADATA WinSockData;
int iWsaStartup;
int iWsaCleanup;
SOCKET UDPSocketClient;
struct sockaddr_in UDPServer;
// STEP-1 Initialization of Winsock
iWsaStartup = WSAStartup(MAKEWORD(2, 2), &WinSockData);
if (iWsaStartup != 0)
{
cout << "WSAStartup Failed = " << iWsaStartup << endl;
}
cout << "WSAStartup Success" << endl;
// STEP-2 Fill the UDPServer Structure
UDPServer.sin_family = AF_INET;
UDPServer.sin_addr.s_addr = inet_addr("169.254.131.8");
UDPServer.sin_port = htons(8001);
// STEP-3 Socket Creation
UDPSocketClient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (UDPSocketClient == INVALID_SOCKET)
{
cout << "Socket Creation Failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "UDP Socket Creation Success" << endl;
int integ = 2656;
//char Buffer[512] = strint;
int iCloseSocket;
while (1)
{
//STEP-4 Sendto Fun.
string strint = to_string(integ);
const char* Buffer = strint.c_str();
int iSendto;
int iBufferLen = strlen(Buffer) + 1;
int iUDPServerLen = sizeof(UDPServer);
cout << integ << endl;
iSendto = sendto(
UDPSocketClient,
Buffer,
iBufferLen,
MSG_DONTROUTE,
(SOCKADDR*)&UDPServer,
sizeof(UDPServer));
if (iSendto == SOCKET_ERROR)
{
cout << "Sending Data Failed " << endl;
cout << "Error No->" << WSAGetLastError() << endl;
}
cout << "Sending Data Success" << endl;
integ = integ + 1;
// STEP-5 CloseSocket Function
}
iCloseSocket = closesocket(UDPSocketClient);
if (iCloseSocket == SOCKET_ERROR)
{
cout << "Socket Closing failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "Close Socket Success" << endl;
// STEP-6 WSACleanUp fun for Terminating the Winsock DLL
iWsaCleanup = WSACleanup();
if (iWsaCleanup == SOCKET_ERROR)
{
cout << "WSA CleanUp failed " << endl;
cout << "Error No-> " << WSAGetLastError() << endl;
}
cout << "Cleanup Success" << endl;
0
system("PAUSE");
return 0;
}
I want to send integer data from the client by an increment of 1 after each loop and receive the respective value on the server side. But I am receiving only the constant integer value "0". I don't know how to do this task.
Thank you

char Buffer[512];
This declares a char array in automatic storage. This char array is completely uninitialized. The next statement:
int iBufferLen = strlen(Buffer) + 1;
This attempts to determine the size of the character string in Buffer, by searching for its terminating \0 byte. That's what strlen() does, after all. It is clear that the intent here is to set iBufferLen to 512, or sizeof(Buffer), instead of to the size of its current string, plus 1, which is obviously incorrect.
Since Buffer is uninitialized, does not contain any character string, and would likely contain random binary garbage, from this point on the shown code is undefined behavior.
If you have not yet learned how to use a debugger, you should consider this to be an excellent opportunity to learn how to do that. If you were to have used your debugger to run your program, one line at a time, your debugger would've immediately shown you that iBufferLen got likely set to 1 or 0, instead of 512.

Related

Can't transfer data from cross-pc using TCP

So I ran my TCP client and server on my own pc, and it worked fine. But when I got my friend to run the client and I ran the server, it came up with Error 10057.
TCP Server:
#include<WinSock2.h>
#include<iostream>
#pragma comment(lib,"ws2_32.lib")
# pragma warning(disable:4996)
using namespace std;
int main()
{
cout << "\t\t------TCP Server-------" << endl;
cout << endl;
WSADATA Winsockdata;
int iWsaStartup;
int iWsaCleanup;
SOCKET TCPServerSocket;
int iCloseSocket;
struct sockaddr_in TCPServerAdd;
struct sockaddr_in TCPClientAdd;
int iTCPClientAdd = sizeof(TCPClientAdd);
int iBind;
int iListen;
SOCKET sAcceptSocket;
int iSend;
char SenderBuffer[512] = "Hello from server";
int iSenderBuffer = strlen(SenderBuffer) + 1;
int iRecv;
char RecvBuffer[512];
int iRecvBuffer = strlen(RecvBuffer) + 1;
//Step-1 WSAStartup Fun------------------------------------
iWsaStartup = WSAStartup(MAKEWORD(2, 2), &Winsockdata);
if (iWsaStartup != 0)
{
cout << "WSAStartup Failed" << endl;
}
cout << "WSAStartup Success" << endl;
// STEP -2 Fill the structure-------------------------------
TCPServerAdd.sin_family = AF_INET;
TCPServerAdd.sin_addr.s_addr = inet_addr("127.0.0.1");
TCPServerAdd.sin_port = htons(8000);
//Step -3 Socket Creation------------------------------------
TCPServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (TCPServerSocket == INVALID_SOCKET)
{
cout << "TCP Server Socket Creation failed" << WSAGetLastError() << endl;
}
//Step -4 bind fun------------------------------------------
iBind = bind(TCPServerSocket, (SOCKADDR*)&TCPServerAdd, sizeof(TCPServerAdd));
if (iBind == SOCKET_ERROR)
{
cout << "Binding Failed &Error No->" << WSAGetLastError() << endl;
}
cout << "Binding success" << endl;
//STEP-5 Listen fun------------------------------------------
iListen = listen(TCPServerSocket, 2);
if (iListen == SOCKET_ERROR)
{
cout << "Listen fun failed &error No->" << WSAGetLastError();
}
cout << "Listen fun success" << endl;
// STEP-6 Accept---------------------------------------------
sAcceptSocket = accept(TCPServerSocket, (SOCKADDR*)&TCPClientAdd, &iTCPClientAdd);
if (sAcceptSocket == INVALID_SOCKET)
{
cout << "Accept failed & Error No ->" << WSAGetLastError() << endl;
}
cout << "Accept fun success" << endl;
// STEP-7 Send Data to the client
iSend = send(sAcceptSocket, SenderBuffer, iSenderBuffer, 0);
if (iSend == SOCKET_ERROR)
{
cout << "Sending Failed & Error No->" << WSAGetLastError() << endl;
}
cout << "Send fun success" << endl;
// STEP -8 Recv Data from Client
iRecv = recv(sAcceptSocket, RecvBuffer, iRecvBuffer, 0);
if (iRecv == SOCKET_ERROR)
{
cout << "Receiving Failed & Error No->" << WSAGetLastError() << endl;
}
cout << "Receive fun success" << endl;
cout << "Data Received -> " << RecvBuffer << endl;
//STEP - 9 Close Socket
iCloseSocket = closesocket(TCPServerSocket);
if (iCloseSocket == SOCKET_ERROR)
{
cout << "Closing Failed & Error No->" << WSAGetLastError() << endl;
}
cout << "Cleanup fun success" << endl;
system("PAUSE");
}
TCP Client
#include<WinSock2.h>
#include<iostream>
#pragma comment(lib,"ws2_32.lib")
# pragma warning(disable:4996)
using namespace std;
int main()
{
cout << "\t\t------TCP Client-------" << endl;
cout << endl;
WSADATA Winsockdata;
int iWsaStartup;
int iWsaCleanup;
SOCKET TCPClientSocket;
int iCloseSocket;
struct sockaddr_in TCPServerAdd;
int iConnect;
int iSend;
char SenderBuffer[512] = "Hello from client";
int iSenderBuffer = strlen(SenderBuffer) + 1;
int iRecv;
char RecvBuffer[512];
int iRecvBuffer = strlen(RecvBuffer) + 1;
//Step-1 WSAStartup Fun------------------------------------
iWsaStartup = WSAStartup(MAKEWORD(2, 2), &Winsockdata);
if (iWsaStartup != 0)
{
cout << "WSAStartup Failed" << endl;
}
cout << "WSAStartup Success" << endl;
//Step -2 Socket Creation------------------------------------
TCPClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (TCPClientSocket == INVALID_SOCKET)
{
cout << "TCP Client Socket Creation failed" << WSAGetLastError() << endl;
}
cout << "TCP client socket creation success";
// STEP -3 Fill the structure-------------------------------
TCPServerAdd.sin_family = AF_INET;
TCPServerAdd.sin_addr.s_addr = inet_addr("127.0.0.1");
TCPServerAdd.sin_port = htons(8000);
// STEP-4 Connect fun---------------------------------------------
iConnect = connect(TCPClientSocket, (SOCKADDR*)&TCPServerAdd, sizeof(TCPServerAdd));
if (iConnect == SOCKET_ERROR)
{
cout << "Connection failed & Error No ->" << WSAGetLastError() << endl;
}
cout << "Connection success" << endl;
// STEP -5 Recv Data from Server
iRecv = recv(TCPClientSocket, RecvBuffer, iRecvBuffer, 0);
if (iRecv == SOCKET_ERROR)
{
cout << "Receiving Failed & Error No->" << WSAGetLastError() << endl;
}
cout << "Receive fun success" << endl;
cout << "Data Received -> " << RecvBuffer << endl;
// STEP-6 Send Data to the server
iSend = send(TCPClientSocket, SenderBuffer, iSenderBuffer, 0);
if (iSend == SOCKET_ERROR)
{
cout << "Sending Failed & Error No->" << WSAGetLastError() << endl;
}
cout << "Data sending success" << endl;
//STEP - 7 Close Socket
iCloseSocket = closesocket(TCPClientSocket);
if (iCloseSocket == SOCKET_ERROR)
{
cout << "Closing Failed & Error No->" << WSAGetLastError() << endl;
}
cout << "Closing Socket success" << endl;
system("PAUSE");
return 0;
}
I have tried editing the ip's on the server to my own port forwarded IP and that didn't work.
I expected me to be able to transfer from the server to the client and the client to the server.
What happened was the Error 10057 occurred.

Bluetooth connection using Winsock c++

I'm currently working on a project trying to connect two PC's using Bluetooth and Winsock, my idea is to develop a server/client connection between them and send a string from the client to the server but unfortunately, it is not working as I was expecting.
When I run the server code it keeps waiting for the client request and only shows in the console "Listen() is ok! Listening for connection". And when I run the client code it runs the entire code until it shows the message "WSACleanUp() works fine". I paired both computers because I thought it was necessary to do so.
My initial guess is that the client connection to the server is not working. I'm new using Winsock and I'm struggling to find accurate information that could help me to fix these issues (besides some questions previously posted and documentation from windows).
Server code
#include<iostream>
#include<WinSock2.h>
#include<ws2bth.h>
#include<bluetoothapis.h>
#include<stdio.h>
#include<string>
#pragma comment (lib, "ws2_32.lib")
#define DEFAULT_BUFLEN 512
DEFINE_GUID(GUID_NULL, "00000000-0000-0000-0000-000000000000");
using namespace std;
void main()
{
//INTIALIZE WINSOCK
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
cerr << "Can't initialize winsok" << endl;
return;
}
//CREATE A BLUETOOTH SOCKET
SOCKET server = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (server == INVALID_SOCKET)
{
cerr << "Can't create a socket" << endl;
return;
}
else
{
cout << "> Server Socket created" << endl;
}
//AUTO ALLOCATION FOR SERVER CHANNEL
SOCKADDR_BTH hint;
memset(&hint, 0, sizeof(hint));
hint.addressFamily = AF_BTH;
hint.port = 0;
hint.btAddr = 0;
hint.serviceClassId = GUID_NULL;
//BINDING
if (bind(server, (sockaddr*)&hint, sizeof(hint)) == SOCKET_ERROR)
{
cout << "Bind() failed with error code: " << WSAGetLastError() << endl;
closesocket(server);
return;
}
else
{
cout << "Bind() is ok" << endl;
cout << "Waiting for client" << endl;
}
//LISTENNING
if (listen(server, SOMAXCONN) == 0)
{
cout << "Listen() is ok! Listening for connection" << endl;
}
else
{
cout << "Listen() failed with error code: " << WSAGetLastError() << endl;
closesocket(server);
return;
}
//WAIT FOR CONNECTION
SOCKADDR_BTH client;
int clientSize;
SOCKET clientSocket;
for (;;)
{
clientSize = sizeof(client);
clientSocket = accept(server, (sockaddr*)&client, &clientSize);
if (clientSocket == INVALID_SOCKET)
{
cout << "Accept() failed with error code: " << WSAGetLastError() << endl;
return;
}
else
{
cout << "Connection accepted" << endl;
printf("Connection came from %04%08x to channel %d\n", GET_NAP(client.btAddr), GET_SAP(client.btAddr), client.port);
}
}
const char *sendbbuf = "Test data from receiver...";
int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN] = "";
int bytesrec;
do
{
//ZeroMemory(buf, 4096);
//WAIT FOR CLIENT TO SEND DATA
bytesrec = recv(clientSocket, recvbuf, recvbuflen, 0);
if (bytesrec > 0)
{
cout << " " << bytesrec << " Bytes received" << endl;
}
else if (bytesrec == 0)
{
cout << "Client disconnected" << endl;
}
else
{
cout << "recv() failed with error code: " << WSAGetLastError() << endl;
}
} while (bytesrec > 0);
//ECHO MESSAGE BACK TO CLIENT
bytesrec = send(clientSocket, recvbuf, bytesrec, 0);
if (bytesrec == SOCKET_ERROR)
{
cout << "Sened() failed with error: " << WSAGetLastError() << endl;
closesocket(clientSocket);
WSACleanup();
return;
}
else
{
cout << "Send() is ok" << endl;
cout << "Bytes sent: " << bytesrec << endl;
}
if (closesocket(server) == 0)
{
cout << "CloseSocket is ok" << endl;
}
if (WSACleanup == 0)
{
cout << "WSACleanUp ok" << endl;
}
return;
}
CLIENT CODDE
#include<iostream>
#include<WinSock2.h>
#include<ws2bth.h>
#include<bluetoothapis.h>
#include<stdio.h>
#include<string.h>
#pragma comment (lib, "ws2_32.lib")
#define DEFAULT_BUFLEN 512
using namespace std;
void main()
{
//SERVER BLUETOOTH ADRESS
//BTH_ADDR addr = 0xB0FC3616D3EE;
//INTIALIZE WINSOCK
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0)
{
cerr << "Can't initialize winsok" << endl;
return;
}
//CREATE A BLUETOOTH SOCKET
SOCKET client = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (client == INVALID_SOCKET)
{
cerr << "Can't create a socket" << endl;
WSACleanup();
return;
}
else
{
cout << "Socket created" << endl;
}
//AUTO ALLOCATION FOR SERVER CHANNEL
SOCKADDR_BTH hint;
memset(&hint, 0, sizeof(hint));
hint.addressFamily = AF_BTH;
hint.port = 0;
hint.btAddr = BTH_ADDR(0xB0FC3616D3EE);
hint.serviceClassId = HandsfreeServiceClass_UUID;
int connResult = connect(client, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR)
{
cerr << "Can't connect to server, ERR #" << WSAGetLastError() << endl;
closesocket(client);
WSACleanup();
return;
}
else
{
cout << "Connected" << endl;
}
const char *sendbuf = "Test data from client..";
int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN] = "";
int res = send(client,sendbuf, (int)strlen(sendbuf), MSG_OOB);
if (res == SOCKET_ERROR)
{
cout << "Send() failed with error code: " << WSAGetLastError() << endl;
closesocket(client);
WSACleanup();
return;
}
else
{
cout << "Send() is ok" << endl;
cout << "Bytes sent: " << res << endl;
}
res = shutdown(client, SD_SEND);
if (res == SOCKET_ERROR)
{
cout << "Shutdown() failed with error code: " << WSAGetLastError() << endl;
closesocket(client);
WSACleanup();
return;
}
else
{
cout << "Shutdown() is working" << endl;
}
//RECEIVE DATA
do
{
res = recv(client, recvbuf, recvbuflen, 0);
if (res > 0)
{
cout << " " << res << " Bytes received from sender" << endl;
}
else if (res == 0)
{
cout << "Client disconnected" << endl;
}
else
{
cout << "recv() failed with code: " << WSAGetLastError() << endl;
}
} while (res > 0);
if (closesocket(client) == 0)
{
cout << "CloseSocket() works fine" << endl;
}
if (WSACleanup() == 0)
{
cout << "WSACleanUp() works fine" << endl;
}

C++ Winsocks, recv(socket,512,0) only receiving one char at a time

For some weird reason, I initialize the sockets:
void init()
{
cout << "\t\t-----TCP SERVER---" << endl;
cout << endl;
//STEP 1 WSAStartup
iwsastartup = WSAStartup(MAKEWORD(2, 2), &Winsockdata);
if (iwsastartup != 0){
cout << "startup failed" << endl;
}
cout << "startup success" << endl;
//STEP 2 fill structure
TCPServerAdd.sin_family = AF_INET;
TCPServerAdd.sin_addr.s_addr = inet_addr("127.0.0.1");
TCPServerAdd.sin_port = htons(8000);
//STEP 3 socket creation
TCPServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (TCPServerSocket == INVALID_SOCKET){
cout << "server socket creation failed: " << WSAGetLastError() << endl;
}
//STEP 4 binding
iBind = ::bind(TCPServerSocket, (SOCKADDR*)&TCPServerAdd, sizeof(TCPServerAdd));
if (iBind == SOCKET_ERROR){
cout << "Binding failed: " << WSAGetLastError() << endl;
}
cout << "binding success" << endl;
iListen = listen(TCPServerSocket, 2);
//STEP 5 listening
if (iListen == SOCKET_ERROR){
cout << "listening failed: " << WSAGetLastError() << endl;
}
cout << "listening..." << endl;
//STEP 6 accept
sAcceptSocket = accept(TCPServerSocket, (SOCKADDR*)&TCPClientAdd, &iTCPClientAdd);
if (sAcceptSocket == INVALID_SOCKET){
cout << "accept failed: " << WSAGetLastError() << endl;
}
cout << "connection accepted" << endl;
}
Where Send and Recv buffers are const char[512], and recieve and send like so:
void recieve_(){
while (true)
{
//STEP 7 recv data from client
iRecv = recv(sAcceptSocket, RecvBuffer, iRecvBuffer, 0);
if (iRecv == SOCKET_ERROR){
cout << "recv failed: " << WSAGetLastError() << endl;
}
else{
//cout << "recv:" << RecvBuffer << endl;
MessageBox(nullptr, LPCWSTR(RecvBuffer), TEXT("Message"), MB_OK);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
init();
//STEP 7 send data to client
thread t1(recieve_);
while (true){
system("PAUSE");
iSend = send(sAcceptSocket, SenderBuffer, iSenderBuffer, 0);
if (iSend == SOCKET_ERROR){
cout << "sending failed: " << WSAGetLastError() << endl;
}
else{
cout << "sent successfully" << endl;
}
}
//STEP 9 close socket
iCloseSocket = closesocket(TCPServerSocket);
closesocket(sAcceptSocket);
WSACleanup();
system("PAUSE");
return 0;
}
Even in a simpler, single threaded version, the buffer is just the first charcter of the sent buffer, eg
char SendBuffer[512] = "Hello";
is recieved as a 512 array with only element 0 set, is this a configuration issue?
Any help appreciated.

SSL_Accept fail, and SSL_get_error return 1

I am new to OpenSSL programming. My task is to write a working SSL proxy.
However, when I start the proxy in Explore, ssl_accept() fails with error code 1.
Why is ssl_accept() failing?
int main(int argc, char **argv){
checkArguments(argc, argv);
initWSA();
int port = atoi(argv[1]);
struct sockaddr_in serverAddr = initAddr(port, std::string(""));
SOCKET Client, Server;
SSL_CTX *server_ctx = clear_method((SSL_METHOD *)TLSv1_1_server_method());
if (!server_ctx)
{
ERR_print_errors_fp(stderr);
std::cout << "ctx error";
}
load_certificate(server_ctx, "C:/Program Files/SnoopSpy/certificate/default.pem", "C:/Program Files/SnoopSpy/certificate/default.pem");
open_socket(Server, serverAddr); //소켓 생성 함수
SSL *server_ssl;
while (true)
{
if ((Client = accept(Server, NULL, NULL)) == INVALID_SOCKET)
{
printf("error : accept\n");
continue;
}
server_ssl = SSL_new(server_ctx); //설정된 Contexxt를 이용하여 SSL 세션의 초기화 작업을 수행한다.
SSL_set_fd(server_ssl, Client);
certificate(server_ssl, 0);
char buf[BUFFER];
memset(buf, NULL, BUFFER);
recv(Client, buf, BUFFER, 0);
cout << buf << endl;
if (server_ssl == NULL)
{
std::cout << "SSL NULL" << std::endl;
}
std::cout << "Connection" << std::endl;
std::cout << "암호키 얻음 : " << SSL_get_cipher(server_ssl) << std::endl;
std::thread(forward, serverAddr, Client, server_ssl).detach();
}
}
void forward(struct sockaddr_in serverAddr, SOCKET Client, SSL *server_ssl)
{
int port = 443;
char buf[BUFFER];
char *recvbuf;
int recvbuflen;
std::string hostAddr, domainip;
SOCKET RemoteSocket;
struct sockaddr_in remoteAddr;
SSL *client_ssl;
int r;
if ((r = SSL_accept(server_ssl)) == -1)
{
int err_SSL_get_error = SSL_get_error(server_ssl, r);
int err_GetLastError = GetLastError();
int err_WSAGetLastError = WSAGetLastError();
int err_ERR_get_error = ERR_get_error();
std::cout << "[DEBUG] SSL_accept() : Failed with return "
<< r << std::endl;
std::cout << "[DEBUG] SSL_get_error() returned : "
<< err_SSL_get_error << std::endl;
std::cout << "[DEBUG] Error string : "
<< ERR_error_string(err_SSL_get_error, NULL)
<< std::endl;
std::cout << "[DEBUG] WSAGetLastError() returned : "
<< err_WSAGetLastError << std::endl;
std::cout << "[DEBUG] GetLastError() returned : "
<< err_GetLastError << std::endl;
std::cout << "[DEBUG] ERR_get_error() returned : "
<< err_ERR_get_error << std::endl;
std::cout << "[DEBUG] GetLastError() returned : "
<< GetLastError << std::endl;
std::cout << "+--------------------------------------------------+"
<< std::endl;
return;
}
while ((recvbuflen = SSL_read(server_ssl, buf, BUFFER)) > 0)
{
SSL_CTX *client_ctx = clear_method((SSL_METHOD *)SSLv23_client_method());
if (client_ctx == NULL)
{
cout << "client ctx error";
break;
}
load_certificate(client_ctx, "C:/Program Files/SnoopSpy/certificate/default.crt", "C:/Program Files/SnoopSpy/certificate/default.key");
recvbuf = (char *)calloc(recvbuflen, sizeof(char));
memcpy(recvbuf, buf, recvbuflen);
hostAddr = getAddr(recvbuf); //여기서 443 포트 번호 확인해야한다.
std::cout << "site : " << hostAddr << endl;
std::cout << "=============================================" << endl;
std::cout << "클라이언트 => 프록시으로 전송 \n";
std::cout << "=============================================" << endl;
std::cout << "포트번호 :" << port << endl;
std::cout << recvbuf << endl;
if (hostAddr == "")
{
printf("Empty Host Address..\n");
break;
}
else
domainip = URLToAddrStr(hostAddr);
if (domainip == "")
{
break;
}
remoteAddr = initAddr(port, domainip); //포트와 도메인 소켓에 넣기
if ((RemoteSocket = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
errorHandle("ERROR : Create a Socket for conneting to server\n", NULL);
}
std::cout << "remote 소켓생성 완료" << endl;
if (connect(RemoteSocket, (struct sockaddr*) &remoteAddr, sizeof(remoteAddr)) == SOCKET_ERROR)
{
std::cout << "연결실패" << endl;
break;
}
if ((client_ssl = SSL_new(client_ctx)) == NULL)
{
cout << "ssl is empty" << endl;
break;
}//자원 할당
SSL_set_fd(client_ssl, RemoteSocket);
if (SSL_connect(client_ssl) == NULL)
{
cout << " ssl not connect" << endl;
break;
}
printf("SSL connection using %s\n", SSL_get_cipher(client_ssl));
std::cout << "remote 연결" << endl;
certificate(client_ssl, 1);
cout << "Success server certificate" << endl;
//다른 쓰레드 function
std::thread(ssl_backward, server_ssl, client_ssl).detach();
if (SSL_write(client_ssl, recvbuf, recvbuflen) == SOCKET_ERROR) //remote
{
printf("send to webserver failed.");
continue;
}
std::cout << "프록시로 보냄\n" << endl;
}
memset(buf, NULL, BUFFER); //NULL 초기화
//closesocket(Client);
//SSL_free(server_ssl);
}
Here is my full code:
https://raw.githubusercontent.com/joongbu/OPENSSL_proxy/master/%EC%86%8C%EC%8A%A4.cpp

Socket issue when include mutex C++

I write a program, that should create a server using a socket in a extra thread. This works well, until I #include <mutex> to my application. But I need to include mutex for another function (not in the example here).
When I include mutex, I get this error when calling bind (marked in code):
error C2440: '=': cannot convert 'std::_Bind' to 'long' in (PATH_TO_PROJECT_LINE_WHERE_BIND_IS_CALLED)
Here is my code:
#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib,"ws2_32.lib")
#include <cstdio>
#include <WinSock2.h>
#include <iostream>
#include <Windows.h>
#include <string>
#include <process.h>
#include <mutex> //if I do not include mutex, everything works
using namespace std;
unsigned int __stdcall threadCreateServer(void*data){
long res;
WSADATA wsaData;
res = WSAStartup(MAKEWORD(2, 0), &wsaData);
if (res == 0){
cout << "[CreateServer] " << "WSAStartup successful" << endl;
}
else {
cout << "[CreateServer] " << "Error WSAStartup" << endl;
return -201;
}
SOCKET slisten, client;
slisten = socket(AF_INET, SOCK_STREAM, 0);
if (slisten != INVALID_SOCKET){
cout << "[CreateServer] " << "Socket() successful" << endl;
}
else{
cout << "[CreateServer] " << "error Socket" << endl;
return -202;
}
sockaddr_in info;
info.sin_addr.s_addr = inet_addr("127.0.0.1");
info.sin_family = AF_INET;
info.sin_port = htons(54126);
res = bind(slisten, (struct sockaddr*)&info, sizeof(info)); //ERROR HERE
if (res != SOCKET_ERROR){
cout << "bind successful" << endl;
}
else {
cout << "ERROR bind" << endl;
return -203;
}
res = listen(slisten, 1);
if (res != SOCKET_ERROR){
cout << "[CreateServer] " << "Listen successful" << endl;
}
else {
cout << "[CreateServer] " << "Listen error" << endl;
return -204;
}
sockaddr_in clientinfo;
int clientinfolen = sizeof(clientinfo);
cout << endl << "~~~~~~~~~" << endl << "[CreateServer] " << "Please connect a client to " << inet_ntoa(info.sin_addr) << ":" << ntohs(info.sin_port) << endl << "~~~~~~~~~" << endl;
client = accept(slisten, (struct sockaddr*)&clientinfo, &clientinfolen);
if (client != SOCKET_ERROR){
cout << "[CreateServer] " << "Client accepted " << inet_ntoa(clientinfo.sin_addr) << ":" << ntohs(clientinfo.sin_port) << endl;
}
else{
cout << "[CreateServer] " << "ERROR client not accepted" << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE handleThreadCreateServer=(HANDLE)_beginthreadex(0,0,&threadCreateServer,0,0,0);
WaitForSingleObject(handleThreadCreateServer, INFINITE);
CloseHandle(handleThreadCreateServer);
return 0;
}
As proposed in a comment, I cannot do using namespace std, because there would be conflicting functions when including mutex.
For everyone, who will have this problem, too:
//to not using namespace std, but:
using std::cout;
using std::endl;
using std::string;
For every other function that isn't used until now, a similar line has to be added. There is not possibllity of using the namespace std and "unusing" std::mutex.