2

Using C# Winforms I am trying to automatically detect the local machines IP address through which it can connect to a particular remote DNS/IP address.

One senario is running over a VPN, with the remote address being 10.8.0.1 and local address being 10.8.0.6, netmask of 255.255.255.252

Iterating through the local addresses and checking if the remote and local are on the same subnet obviously fails and I am unsure of how else to do this.

4

3 回答 3

0

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

于 2012-04-22T21:10:18.920 回答
0

这是一些示例代码,可以为您提供所需的信息。它创建一个 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# 中。

于 2013-01-03T14:45:59.087 回答
-1

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

试一试。

于 2012-04-22T20:59:52.047 回答