簡體   English   中英

如何確定可以連接到給定遠程IP / DNS地址的本地IP地址

[英]How do I determine local IP address which can connect to a given remote IP/DNS Address

使用C#Winforms,我試圖自動檢測本地計算機的IP地址,通過它可以連接到特定的遠程DNS / IP地址。

一個senario通過VPN運行,遠程地址為10.8.0.1,本地地址為10.8.0.6,網絡掩碼為255.255.255.252。

遍歷本地地址並檢查遠程和本地是否在同一子網中顯然會失敗,並且我不確定如何執行此操作。

路由表確定要使用的本地端口。 除了運行route print CLI命令外,我不知道從C#中獲取它的方法。 如果網絡匹配,則使用該端口,否則使用默認路由。

這是一些示例代碼,可以為您提供所需的信息。 它創建一個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#。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM