【问题标题】:How do I determine local IP address which can connect to a given remote IP/DNS Address如何确定可以连接到给定远程 IP/DNS 地址的本地 IP 地址
【发布时间】:2012-04-22 20:57:29
【问题描述】:

使用 C# Winforms 我试图自动检测本地机器的 IP 地址,通过它可以连接到特定的远程 DNS/IP 地址。

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

遍历本地地址并检查远程和本地是否在同一个子网上显然失败了,我不确定该怎么做。

【问题讨论】:

    标签: c# .net network-programming


    【解决方案1】:

    下面是一些示例代码,可以为您提供所需的信息。它创建一个 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();
    }
    

    请注意,这实际上是 this answer 的实现,但在 C# 中。

    【讨论】:

      【解决方案2】:

      routing table 决定使用哪个本地端口。除了运行 route print CLI 命令之外,我不知道从 C# 获取它的方法。如果有网络匹配,则使用该端口,否则使用默认路由。

      【讨论】:

        【解决方案3】:

        【讨论】:

        • 这不是 OP 所要求的。在具有多个 IP 的主机上,他想知道在联系另一台主机时如何确定哪些将用作本地地址。
        猜你喜欢
        • 1970-01-01
        • 2011-11-12
        • 1970-01-01
        • 2011-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 2020-11-29
        相关资源
        最近更新 更多