获取默认网关 [英] Get the Default Gateway

查看:306
本文介绍了获取默认网关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个程序,显示用户自己的IP地址,子网掩码和默认网关。我能得到的前两个,但最后一个,这是我打开了:

I'm writing a program that shows the user their IP address, Subnet mask and Default gateway. I can get the first two, but for the last one, this is what I turned up:

GatewayIPAddressInformationCollection gwc = 
    System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].GetIPProperties().GatewayAddresses;

这,当然,返回 GatewayIPAddressInformation 的集合。所以,如果计算机有多个网关,我怎么能确定这是的默认的网关?

That, of course, returns a collection of GatewayIPAddressInformation. So, if a computer has multiple gateways, how can I determine which is the default gateway?

在实践中,我只看过这个系列包含一个条目,但因为它是作为一个集合实现的,按理说,有些计算机包含多个网关,其中没有一个被标记为默认。那么,有没有一种方法来确定的默认的还是这一切只是凭空猜测?

In practice, I've only ever seen this collection contain a single entry, but since it's implemented as a collection, it stands to reason that some computers contain multiple gateways, none of which are marked as "Default". So is there a way to determine the default or is it all just guesswork?

推荐答案

它应该永远是第一位的:

It should always be the first one:

public static IPAddress GetDefaultGateway()
{
    var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();
    if(card == null) return null;
    var address = card.GetIPProperties().GatewayAddresses.FirstOrDefault();
    return address.Address;
}

这篇关于获取默认网关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆