I am trying to create C++ socket client for python server. Because I am new to C++ before creating the C++ client I checked if the python socket server with python client. After creating and running the C++ client the server do not get any connection
server.py
def start_listener():
ip = "0.0.0.0"
port = 4444
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Tying to bind
server.bind((ip, port))
server.listen(3)
print("[+] Server bind on %s:%d" %(ip,port))
except socket.error as error:
print("[!] Unable to bind on %s:%d" %(ip,port))
# Waiting for connections and handle them
while True:
print("Wating for connections...")
# Waiting part
connenction, addr = server.accept()
print("[+] Accecpted connection from %s:%d" % (addr[0],addr[1]))
data = connenction.recv(2000).decode()
print(data)
start_listener()
ClientSocket.cpp:
#include "ClientSocket.h"
#include <iostream>
ClientSocket::ClientSocket(string ip, int port) {
socket_ip = ip;
socket_port = port;
}
void ClientSocket::CreateSession(){
ClientSocket::sock = socket(AF_INET, SOCK_STREAM, 0);
if(ClientSocket::sock < 0){
cout << "[!] Unable to create socket" << endl;
}
struct sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr((ClientSocket::socket_ip).c_str());
serv_addr.sin_port = htons(ClientSocket::socket_port);
if(connect(ClientSocket::sock, (SOCKADDR *)&serv_addr ,sizeof(sockaddr)) < 0){
cout << "[!] Unable to connect to remote socket" << endl;
}
}
ClientSocket.h
#include <string>
#include <list>
#include <winsock2.h>
#include <Ws2tcpip.h>
using namespace std;
#ifndef SOCKET_H
#define SOCKET_H
class ClientSocket {
private:
string socket_ip;
int socket_port;
SOCKET sock;
public:
ClientSocket(string ip, int port);
void PrintSocket();
void CreateSession();
void SendData(string data);
};
#endif // SOCKET_H
main.cpp
#include "ClientSocket.h"
using namespace std;
int main() {
ClientSocket clientsocket ("127.0.0.1", 4444);
clientsocket.CreateSession();
return 0;
}
output
[!] Unable to connect to remote socket
After including <errno.h>
and print the error its print no error
Add
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 0), &wsaData);
before creating the client socket to initialize winsock2
So it should look like this:
void CreateSession() {
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 0), &wsaData);
this->sock = socket(AF_INET, SOCK_STREAM, 0);
if (this->sock < 0) {
cout << "[!] Unable to create socket" << endl;
}
struct sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr((ClientSocket::socket_ip).c_str());
serv_addr.sin_port = htons(ClientSocket::socket_port);
if (connect(this->sock, (SOCKADDR*)&serv_addr, sizeof(sockaddr)) == SOCKET_ERROR) {
cout << "[!] Unable to connect to remote socket" << endl;
}
}