你能绑定()和连接()UDP连接的两端吗 [英] Can you bind() and connect() both ends of a UDP connection

查看:17
本文介绍了你能绑定()和连接()UDP连接的两端吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个点对点消息队列系统,它必须能够通过 UDP 运行.我可以任意选择一侧或另一侧作为服务器",但这似乎不太正确,因为两端都在从另一端发送和接收相同类型的数据.

I'm writing a point-to-point message queue system, and it has to be able to operate over UDP. I could arbitrarily pick one side or the other to be the "server" but it doesn't seem quite right since both ends are sending and receiving the same type of data from the other.

是否可以绑定()和连接()两端,以便它们只相互发送/接收?这似乎是一种很好的对称方式.

Is it possible to bind() and connect() both ends so that they send/receive only from each other? That seems like a nicely symmetric way to do it.

推荐答案

你好,从遥远的未来,即 2018 年,到 2012 年.

Hello from the distant future which is the year 2018, to the year 2012.

事实上,在实践中 connect() 使用 UDP 套接字是有原因的(尽管有福的 POSIX 及其实现理论上不需要你这样做).

There's, in fact, a reason behind connect()ing an UDP socket in practice (though blessed POSIX and its implementations don't in theory require you to).

一个普通的 UDP 套接字不知道它未来的目的地,所以 每次调用 sendmsg() 时都会执行一次路由查找.

An ordinary UDP socket doesn't know anything about its future destinations, so it performs a route lookup each time sendmsg() is called.

但是,如果预先使用特定远程接收器的 IP 和端口调用 connect(),操作系统内核将能够 写下对路由的引用并将其分配给套接字,从而显着加快如果后续 sendmsg() 调用不指定接收者(否则之前的设置会被忽略),而是选择默认的.

However, if connect() is called beforehand with a particular remote receiver's IP and port, the operating system kernel will be able to write down the reference to the route and assign it to the socket, making it significantly faster to send a message if subsequent sendmsg() calls do not specify a receiver (otherwise the previous setting would be ignored), choosing the default one instead.

查看10701171:

if (connected)
    rt = (struct rtable *)sk_dst_check(sk, 0);

if (!rt) {
    [..skip..]

    rt = ip_route_output_flow(net, fl4, sk);

    [..skip..]
}

在 Linux 内核 4.18 之前,此功能主要仅限于 IPv4 地址系列.但是,从 4.18-rc4(希望 Linux 内核版本 4.18 也是如此)开始,完全也可与 IPv6 套接字一起使用.

Until Linux kernel 4.18, this feature had been mostly limited to the IPv4 address family only. However, since 4.18-rc4 (and hopefully Linux kernel release 4.18 as well), it's fully functional with IPv6 sockets as well.

它可能是严重性能优势的来源,尽管它在很大程度上取决于您使用的操作系统.至少,如果您使用的是 Linux 并且不将套接字用于多个远程处理程序,您应该尝试一下.

It may be a source of a serious performance benefit, though it will heavily depend on the OS you're using. At least, if you're using Linux and don't use the socket for multiple remote handlers, you should give it a try.

这篇关于你能绑定()和连接()UDP连接的两端吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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