从一台服务器监听多个端口 [英] Listen to multiple ports from one server

查看:65
本文介绍了从一台服务器监听多个端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在一个应用程序中绑定和侦听 Linux 中的多个端口?

Is it possible to bind and listen to multiple ports in Linux in one application?

推荐答案

对于您想要监听的每个端口,您:

For each port that you want to listen to, you:

  1. socket创建一个单独的socket.
  2. 使用 bind 将其绑定到适当的端口.
  3. 在套接字上调用 listen 以设置监听队列.
  1. Create a separate socket with socket.
  2. Bind it to the appropriate port with bind.
  3. Call listen on the socket so that it's set up with a listen queue.

此时,您的程序正在侦听多个套接字.为了接受这些套接字上的连接,您需要知道客户端连接到哪个套接字.这就是 select 的用武之地.碰巧的是,我有代码可以做到这一点,所以这里有一个完整的测试示例,它等待多个套接字上的连接并返回连接的文件描述符.远程地址在附加参数中返回(缓冲区必须由调用者提供,就像accept一样).

At that point, your program is listening on multiple sockets. In order to accept connections on those sockets, you need to know which socket a client is connecting to. That's where select comes in. As it happens, I have code that does exactly this sitting around, so here's a complete tested example of waiting for connections on multiple sockets and returning the file descriptor of a connection. The remote address is returned in additional parameters (the buffer must be provided by the caller, just like accept).

(socket_type 这里是 Linux 系统上 int 的 typedef,INVALID_SOCKET-1.那些是否存在,因为此代码也已移植到 Windows.)

(socket_type here is a typedef for int on Linux systems, and INVALID_SOCKET is -1. Those are there because this code has been ported to Windows as well.)

socket_type
network_accept_any(socket_type fds[], unsigned int count,
                   struct sockaddr *addr, socklen_t *addrlen)
{
    fd_set readfds;
    socket_type maxfd, fd;
    unsigned int i;
    int status;

    FD_ZERO(&readfds);
    maxfd = -1;
    for (i = 0; i < count; i++) {
        FD_SET(fds[i], &readfds);
        if (fds[i] > maxfd)
            maxfd = fds[i];
    }
    status = select(maxfd + 1, &readfds, NULL, NULL, NULL);
    if (status < 0)
        return INVALID_SOCKET;
    fd = INVALID_SOCKET;
    for (i = 0; i < count; i++)
        if (FD_ISSET(fds[i], &readfds)) {
            fd = fds[i];
            break;
        }
    if (fd == INVALID_SOCKET)
        return INVALID_SOCKET;
    else
        return accept(fd, addr, addrlen);
}

此代码不会告诉调用者客户端连接到哪个端口,但您可以轻松添加一个 int * 参数,该参数将获取看到传入连接的文件描述符.

This code doesn't tell the caller which port the client connected to, but you could easily add an int * parameter that would get the file descriptor that saw the incoming connection.

这篇关于从一台服务器监听多个端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆