【发布时间】: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
使用 C# Winforms 我试图自动检测本地机器的 IP 地址,通过它可以连接到特定的远程 DNS/IP 地址。
一个场景在 VPN 上运行,远程地址为 10.8.0.1,本地地址为 10.8.0.6,网络掩码为 255.255.255.252
遍历本地地址并检查远程和本地是否在同一个子网上显然失败了,我不确定该怎么做。
【问题讨论】:
标签: c# .net network-programming
下面是一些示例代码,可以为您提供所需的信息。它创建一个 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# 中。
【讨论】:
routing table 决定使用哪个本地端口。除了运行 route print CLI 命令之外,我不知道从 C# 获取它的方法。如果有网络匹配,则使用该端口,否则使用默认路由。
【讨论】:
【讨论】: