gpt4 book ai didi

c++ - C++套接字客户端到python服务器未创建连接

转载 作者:行者123 更新时间:2023-12-02 10:21:02 25 4
gpt4 key购买 nike

我正在尝试为python服务器创建C++套接字客户端。
因为在创建C++客户端之前我是C++的新手,所以我检查了python套接字服务器是否带有python客户端。创建并运行C++客户端后,服务器未获得任何连接

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;
}

输出
[!] Unable to connect to remote socket

包含 <errno.h>并打印错误后,其打印没有错误

最佳答案

添加

WSADATA wsaData;
WSAStartup(MAKEWORD(2, 0), &wsaData);

在创建客户端套接字 initialize winsock2之前

所以它应该看起来像这样:
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;
}
}

关于c++ - C++套接字客户端到python服务器未创建连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60137903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com