【发布时间】:2014-12-20 08:49:49
【问题描述】:
这是一个基于 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、端口 1 的特定客户端?例如检查 ip 127.0.0.1 和端口 44852 的客户端是否已经连接?如果已连接打印,则所需的客户端已经可用。任何人都可以建议我这样做吗?
【问题讨论】:
-
您说您使用的是 UDP,但此代码用于 TCP。您不能将
listen()和accept()与 UDP 一起使用。