我想在不同的端口上绑定 4 个套接字。不知何故,我总是得到: Address already in use
错误。对于第一个循环,case PORT1
它正在工作,但是在第二次运行时,我得到了上述错误。如果有人可以仔细查看我的代码,那就太好了。
输出如下所示:
thread 0 started, pc_packet_receiver
sock_fd[8]
sock_fd[8], fdmax[8]
sock_fd[9]
error: could not bind UDP socket, port2
: Address already in use
如您所见,printf
循环中的第一个被处理了两次,并且何时bind
调用PORT2
程序崩溃。
sock_fd
是一个文件描述符数组sock_addr_port[1..4]
是四个不同的struct sock_addr
- 这些值
PORT1/PORT2/PORT3/PORT4
被定义在一个enum [1..4]
- 最后,我想将所有内容添加
sock_fd[i]
到 aFD_SET
中以处理它们select
非常感谢您的帮助。
for(i = 0; i < 4; i++) {
if((sock_fd[i] = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("error: could not open UDP socket\n");
exit(EXIT_FAILURE);
}
printf("\tsock_fd[%d]\n", sock_fd[i]);
switch (i+1) {
case PORT1:
bzero(&sock_addr_port1, sock_len_port1);
sock_addr_port1.sin_family = AF_INET;
sock_addr_port1.sin_port = htons(ETH_PORT1);
sock_addr_port1.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port1, sock_len_port1) < 0) {
perror("error: could not bind UDP socket, port1\n");
exit(EXIT_FAILURE);
}
break;
case PORT2:
bzero(&sock_addr_port2, sock_len_port2);
sock_addr_port2.sin_family = AF_INET;
sock_addr_port2.sin_port = htons(ETH_PORT2);
sock_addr_port2.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port2, sock_len_port2) < 0) {
perror("error: could not bind UDP socket, port2\n");
exit(EXIT_FAILURE);
}
break;
case PORT3:
bzero(&sock_addr_port3, sock_len_port3);
sock_addr_port3.sin_family = AF_INET;
sock_addr_port3.sin_port = htons(ETH_PORT3);
sock_addr_port3.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port3, sock_len_port3) < 0) {
perror("error: could not bind UDP socket, port3\n");
exit(EXIT_FAILURE);
}
break;
case PORT4:
bzero(&sock_addr_port4, sock_len_port4);
sock_addr_port4.sin_family = AF_INET;
sock_addr_port4.sin_port = htons(ETH_PORT4);
sock_addr_port4.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sock_fd[i], (struct sockaddr *) &sock_addr_port4, sock_len_port4) < 0) {
perror("error: could not bind UDP socket, port4\n");
exit(EXIT_FAILURE);
}
break;
default:
break;
}
FD_SET(sock_fd[i], &read_fds);
fdmax = sock_fd[i];
printf("sock_fd[%d], fdmax[%d]\n", sock_fd[i], fdmax);
}