将UDP套接字绑定到特定的本地终结点

本文关键字:结点 UDP 套接字 绑定 | 更新日期: 2023-09-27 17:58:30

我这样做:

Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(new IPAddress(new byte[] {192, 168, 1, 8}), 45678));
socket.BeginConnect(new IPEndPoint(new IPAddress(new byte[] { 65, 52, 108, 52 }), 80), null, null);
socket.Send(new byte[] { 1, 2, 3 });

但是套接字实际上并没有绑定到本地IP地址192.168.1.8,只有端口:

UDP    0.0.0.0:45678          *:*

为什么?

将UDP套接字绑定到特定的本地终结点

我为套接字使用了错误的重载构造函数:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(new IPAddress(new byte[] {192, 168, 1, 8}), 45678));
socket.BeginConnect(new IPEndPoint(new IPAddress(new byte[] { 65, 52, 108, 52 }), 80), null, null);
socket.Send(new byte[] { 1, 2, 3 });

现在它被正确绑定:

 UDP    192.168.1.8:45678      *:*