C /绑定多个套接字[在不同的端口上]

时间:2012-05-23 08:08:42

标签: c sockets

我想在不同的端口绑定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/PORT4enum [1..4]
  • 中定义
  • 最后我想将所有sock_fd[i]添加到FD_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);
}

1 个答案:

答案 0 :(得分:0)

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

谷歌“哪个进程使用哪个端口”来了解如何找到该进程。