如何使用boost :: asio连接到unix域套接字?

时间:2016-05-06 20:09:49

标签: c++ sockets boost boost-asio

我想通过指定套接字端点的路径名来创建并连接到unix domain socket类型的SOCK_SEQPACKET,但这无法在boost::asio v1.60中编译:

using namespace boost::asio::generic;
seq_packet_protocol proto{AF_UNIX, IPPROTO_SCTP}; // SOCK_SEQPACKET
seq_packet_protocol::socket sock(io_service, proto);
boost::asio::local::basic_endpoint<seq_packet_protocol> ep("/tmp/socket");
sock.connect(ep); // does not compile

你知道如何正确创建一个unix域套接字吗?

2 个答案:

答案 0 :(得分:4)

我建议保持简单:

#include <boost/asio.hpp>

int main() {
    boost::asio::io_service io_service;
    using boost::asio::local::stream_protocol;

    stream_protocol::socket s(io_service);
    s.connect("/tmp/socket");
}

毫无疑问,你可以更低级别,但我不确定你什么时候需要它。

更新模仿预定义的stream_protocol,以下是seqpacket_protocol的定义方式:

<强> Live On Coliru

namespace SeqPacket {
    using namespace boost::asio::local;

    struct seqpacket_protocol
    {
        int type()     const { return IPPROTO_SCTP; }
        int protocol() const { return 0;            }
        int family()   const { return AF_UNIX;      }

        typedef basic_endpoint<seqpacket_protocol> endpoint;
        typedef boost::asio::basic_stream_socket<seqpacket_protocol> socket;
        typedef boost::asio::basic_socket_acceptor<seqpacket_protocol> acceptor;

#if !defined(BOOST_ASIO_NO_IOSTREAM)
        /// The UNIX domain iostream type.
        typedef boost::asio::basic_socket_iostream<seqpacket_protocol> iostream;
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
    };
}

只需以相同的模式使用它:

int main() {
    boost::asio::io_service io_service;
    using SeqPacket::seqpacket_protocol;

    seqpacket_protocol::socket s(io_service);
    s.connect("socket");
}

答案 1 :(得分:0)

要补充这些答案,套接字定义是错误的,应该是:

typedef boost::asio::basic_seq_packet_socket<seqpacket_protocol> socket;

将其放在一起:

namespace SeqPacket {
    struct seqpacket_protocol
    {
        int type()     const { return SOCK_SEQPACKET; }
        int protocol() const { return 0;            }
        int family()   const { return AF_UNIX;      }

        typedef boost::asio::local::basic_endpoint<seqpacket_protocol> endpoint;
        typedef boost::asio::basic_seq_packet_socket<seqpacket_protocol> socket;
        typedef boost::asio::basic_socket_acceptor<seqpacket_protocol> acceptor;

#if !defined(BOOST_ASIO_NO_IOSTREAM)
        /// The UNIX domain iostream type.
        typedef boost::asio::basic_socket_iostream<seqpacket_protocol> iostream;
#endif // !defined(BOOST_ASIO_NO_IOSTREAM)
    };
}