【发布时间】:2014-04-01 01:21:16
【问题描述】:
我正在使用 winsocks 并且正在编写 IDS/Honeypot,这只是其中的一小部分,因为目前我希望服务器侦听多个套接字 (7) 并接受连接,但是我'我尝试使用数组(和侦听器等)动态创建套接字,但我仍然遇到问题 - 我已经尝试了多种方法,但到目前为止,我所做的只是让它在一个套接字上成功工作,并监听所有套接字,但不接受它们。
所以,这是我最后一次尝试,但不确定,也许我需要使用线程或以不同的方式声明套接字?
到目前为止,在这个小测试代码中,我想要:
初始化服务器 监听所有 7 个端口(1111,2222 ...等) 接受其中任何一个的传入连接 在客户端/服务器上显示两条消息 断开连接 并继续
我知道这有点草率,但这是到目前为止的代码,我想你可以看到我的目标:
#include <iostream>
#include <winsock2.h>
#include <string>
#pragma comment(lib, "ws2_32.lib")
int main()
{
std::cout<<"Honeypot server [test #1] by Dreamwalker"<<std::endl;
WSADATA wsa;
SOCKET s[7] , new_socket[7];
struct sockaddr_in server , client;
int c, port[7] = {1111,2222,3333,4444,5555,6666,7777};
char *message;
std::cout<<"\nInitialising Winsock and other components...";
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
std::cout<<"Failed. Error Code :"<<WSAGetLastError()<<std::endl;
return 1;
}
//!IMPORTANT: create multiple new sockets on different ports
int i = 0;
for( i = 0; i < 7; i++)
{
//Create socket
if((s[i] = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
std::cout<<"Could not create socket : "<< WSAGetLastError()<<std::endl;
}
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( port[i] );
//Bind
if( bind(s[i] ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
std::cout<<"Bind failed with error code : "<< WSAGetLastError()<<std::endl;
}
/*!ALL CREATION CHECKING DONE, now create multiple sockets on the server
and listen for connections*/
c = sizeof(struct sockaddr_in);
listen(s[i] , SOMAXCONN);
}
///ALL INITIALIZED
std::cout<<"DONE!"<<std::endl;
//Listen/accept incoming connections
std::cout<<"Now listening for connections"<<std::endl;
new_socket[i] = accept(s[i] , (struct sockaddr *)&client, &c);
if (new_socket[i] == INVALID_SOCKET)
{
std::cout<<"accept failed with error code : "<< WSAGetLastError()<<std::endl;
}
//Accepted connection
else{
std::cout<<"Someone has connected to this machine!"<<std::endl;
message = "Hello Client , I have received your connection.\n";
send(new_socket[i] , message , strlen(message) , 0);
closesocket(s[i]);
}
std::cout<<"FINISHED"<<std::endl;
WSACleanup();
getchar();
return 0;
}
现在它也抛出了运行时错误:
WSAENOTSOCK 10038 Socket operation on nonsocket. An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket,或者对于 select,fd_set 的成员无效。
哪个(包括调试)表明在数组上创建时未正确声明套接字,建议?
【问题讨论】: