我知道如果IP不属于子网掩码+本地IP规则,则只能通过网关访问。问题是我不知道如何使用.NET以编程方式获取本地IP地址,也不知道本地子网掩码。 你们中的任何一个可以帮助我吗?
我将使用此信息从我的批处理SQL插入队列中挤出最大性能。如果SQL服务器属于同一子网,那么它将使用针对最小延迟优化的算法,否则我将使用针对高延迟优化的算法。
答案 0 :(得分:10)
您可以使用System.Net.NetworkInformation命名空间(在.NET 2.0中引入)中的类:
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface iface in interfaces)
{
IPInterfaceProperties properties = iface.GetIPProperties();
foreach (UnicastIPAddressInformation address in properties.UnicastAddresses)
{
Console.WriteLine(
"{0} (Mask: {1})",
address.Address,
address.IPv4Mask
);
}
}
答案 1 :(得分:4)
使用NetworkInformation类还有另一种方法:
public static void ShowNetworkInterfaces()
{
// IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
if (nics == null || nics.Length < 1)
{
Console.WriteLine(" No network interfaces found.");
return;
}
Console.WriteLine(" Number of interfaces .................... : {0}", nics.Length);
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
Console.WriteLine();
Console.WriteLine(adapter.Description);
Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'='));
Console.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType);
Console.WriteLine(" Physical Address ........................ : {0}", adapter.GetPhysicalAddress().ToString());
string versions ="";
// Create a display string for the supported IP versions.
if (adapter.Supports(NetworkInterfaceComponent.IPv4))
{
versions = "IPv4";
}
if (adapter.Supports(NetworkInterfaceComponent.IPv6))
{
if (versions.Length > 0)
{
versions += " ";
}
versions += "IPv6";
}
Console.WriteLine(" IP version .............................. : {0}", versions);
UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses;
if (uniCast != null)
{
foreach (UnicastIPAddressInformation uni in uniCast)
{
Console.WriteLine(" Unicast Address ......................... : {0}", uni.Address);
Console.WriteLine(" Subnet Mask ......................... : {0}", uni.IPv4Mask);
}
}
Console.WriteLine();
}
}
代码示例是一个mashup表单,由Msdn提供的示例,简化为仅显示您可能需要的信息。
编辑:花了太长时间(太多事情同时:) :)发表这篇文章,米奇打败了我:)答案 2 :(得分:1)
这将获取主机名和IP地址。我假设您知道局域网中的IP,因此您应该能够确定IP地址是否在局域网之外:
// Get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
// Using the host name, get the IP address list.
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}