这是UDP上的基本客户端服务器程序。如果客户端1发送数据,则客户端2将接收,反之亦然。
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
//bind the socket to localhost port 1902
if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("Listener on port %d \n", PORT);
if (listen(master_socket, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
//accept the incoming connection
addrlen = sizeof(address);
puts("Waiting for connections ...");
while(TRUE)
{
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(master_socket, &readfds);
max_sd = master_socket;
//add child sockets to set
for ( i = 0 ; i < max_clients ; i++)
{
//socket descriptor
sd = client_socket[i];
//if valid socket descriptor then add to read list
if(sd > 0)
FD_SET( sd , &readfds);
//highest file descriptor number, need it for the select function
if(sd > max_sd)
max_sd = sd;
}
//wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely
activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL);
if ((activity < 0) && (errno!=EINTR))
{
printf("select error");
}
//If something happened on the master socket , then its an incoming connection
if (FD_ISSET(master_socket, &readfds))
{
if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
//inform user of socket number - used in send and receive commands
printf("New connection , socket fd is %d , ip is : %s , port : %d \n" , new_socket , inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
....
....
//what has to be done here to check a client with IP1, Port 1 is already connected? //
....
....
}
}
在这个程序中,我收到了一条消息
New connection , socket fd is 4 , ip is : 127.0.0.1 , port : 44851
Welcome message sent successfully
Adding to list of sockets as 0
New connection , socket fd is 5 , ip is : 127.0.0.1 , port : 44852
Welcome message sent successfully
Adding to list of sockets as 1
在此消息之后,我想检查是否连接了IP1,PORT 1的特定客户端?例如检查ip 127.0.0.1和端口44852的客户端是否已连接?如果连接打印,所需的客户端已经可用。任何人都可以建议我这样做吗?
答案 0 :(得分:0)
如何做到这一点应该是非常明显的。您将客户端信息存储在列表中。因此,只需循环检查列表,检查accept()
报告的ip / port是否已经在列表中,如果没有则添加它。只要确保在客户端断开连接时保持列表最新。