Answer the question
In order to leave comments, you need to log in
What if listen returns 10022?
I am writing a TCP server in MFC.
I initialize like this:
CCYBERRMSDlg* dlg = (CCYBERRMSDlg*)Param;
CString ip, port;
dlg->GetDlgItem(IDC_EDIT2)->GetWindowTextA(ip);
dlg->GetDlgItem(IDC_EDIT3)->GetWindowTextA(port);
string IP, PORT;
IP = string(CT2CA(ip));
PORT = string(CT2CA(port));
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
if (WSAStartup(DllVersion, &wsaData) != 0) {
return false;
}
SOCKADDR_IN addr;
int sizeofaddr = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(IP.c_str());
addr.sin_port = atoi(PORT.c_str());
SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
if (WSAGetLastError() != 0) {
dlg->AddLog("bind error");
return -1;
}
if (listen(sListen, SOMAXCONN) != 0) {
dlg->AddLog("listen error");
return -1;
}
Answer the question
In order to leave comments, you need to log in
I did not understand what the problem was, but it seems to me that it was necessary to use ::bind
and not bind
Found a working code here: https://www.binarytides.com/code-tcp-socket-server...
WSACleanup();
WSADATA wsaData;
SOCKET sListen, newConnection;
struct sockaddr_in server, client;
int c;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
dlg->AddLog("Error WSAStartup");
return -1;
}
if ((sListen = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
dlg->AddLog("Error create socket sListen");
return -1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(IP.c_str());
server.sin_port = htons(atoi(PORT.c_str()));
int result = ::bind(sListen, (struct sockaddr*)&server, sizeof(server));
if (result != 0) {
string code = to_string(WSAGetLastError());
dlg->AddLog(string("Bind error: " + code).c_str());
}
listen(sListen, 256);
dlg->AddLog("Waiting for connections...");
c = sizeof(struct sockaddr_in);
newConnection = accept(sListen, (struct sockaddr*)&client, &c);
if (newConnection == INVALID_SOCKET) {
dlg->AddLog("Error accept");
}
dlg->AddLog("Connected new user!");
closesocket(sListen);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question