如何确定可以连接到给定远程 IP/DNS 地址的本地 IP 地址



使用C# Winforms,我正在尝试自动检测本地计算机IP地址,通过该地址可以连接到特定的远程DNS/IP地址。

一个Senario正在VPN上运行,远程地址为10.8.0.1,本地地址为10.8.0.6,网络掩码为255.255.255.252

遍历本地地址并检查远程地址和本地地址是否在同一子网上显然失败了,我不确定如何做到这一点。

下面是一些示例代码,应该可以为您提供所需的信息。 它创建一个 UDP 套接字并在其上调用Connect()(实际上是 NOOP),然后检查本地地址。

static EndPoint GetLocalEndPointFor(IPAddress remote)
{
    using (Socket s = new Socket(remote.AddressFamily,
                                 SocketType.Dgram,
                                 ProtocolType.IP))
    {
        // Just picked a random port, you could make this application
        // specific if you want, but I don't think it really matters
        s.Connect(new IPEndPoint(remote, 35353));
        return s.LocalEndPoint;
    }
}
static void Main(string[] args)
{
    IPAddress remoteAddress = IPAddress.Parse("10.8.0.1");
    IPEndPoint localEndPoint = GetLocalEndPointFor(remoteAddress) as IPEndPoint;
    if (localEndPoint == null)
        Console.WriteLine("Couldn't find local address");
    else
        Console.WriteLine(localEndPoint.Address);
    Console.ReadKey();
}

请注意,这实际上是此答案的实现,但在 C# 中。

路由表确定要使用的本地端口。 我不知道从 C# 获得它的方法,除了运行路由打印 CLI 命令。 如果存在网络匹配,则使用该端口,否则使用默认路由。

http://www.csharp-examples.net/local-ip/

一试。

最新更新