0

我想在不同的端口上绑定 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);
}
4

1 回答 1

0

ETH_PORT2现在正在运行另一个进程。netstat -tan当您在命令行上运行(-tn在 Windows 上)时,您应该能够看到这一点。

谷歌“哪个进程使用哪个端口”,看看你如何找到这个进程。

于 2012-05-23T08:18:00.317 回答