1

I have a program shown below:

Socket receiveSocket = new Socket(AddressFamily.InterNetwork,
                                  SocketType.Dgram, ProtocolType.Udp);

EndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, 3838);

byte[] recBuffer = new byte[256];

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    receiveSocket.Bind(bindEndPoint);
    receiveSocket.Receive(recBuffer);
}

and it is working but when I want to just listen to a specific IP address it does not work, it throws an exeption "the requested address is not valid in context"

new code: EndPoint bindEndPoint = new IPEndPoint(IPAddress.Parse("192.168.40.1"), 3838);

4

1 回答 1

2

您绑定的 IP 地址应该是实际分配给您计算机上的网络接口的 IP 地址之一。

假设您有一个以太网接口和一个无线接口

以太网:192.168.1.40

无线:192.168.1.42

在套接字上调用 Bind 方法时,是在告诉它要在哪个接口上侦听数据。例如,要么是“其中任何一个”,要么只是以太网接口。

我猜这不是你要找的吗?

也许您正试图限制谁可以连接到您的服务器

所以你可能正在寻找的是

var remoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.40"), 0)
receiveSocket.ReceiveFrom(buffer, remoteEndpoint);

这限制了您接受数据的来源。

于 2012-04-04T08:37:56.520 回答