C# 获取本机真实网关


        /// 
        /// 尝试Ping指定IP是否能够Ping通
        /// 
        /// 指定IP
        /// true 是 false 否
        public static bool IsPingIP(string strIP)
        {
            try
            {
                //创建Ping对象
                Ping ping = new Ping();
                //接受Ping返回值
                PingReply reply = ping.Send(strIP, 1000);
                //Ping通
                return true;
            }
            catch
            {
                //Ping失败
                return false;
            }
        }

        //得到网关地址
        public static string GetGateway()
        {
            //网关地址
            string strGateway = "";
            //获取所有网卡
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            //遍历数组
            foreach (var netWork in nics)
            {
                //单个网卡的IP对象
                IPInterfaceProperties ip = netWork.GetIPProperties();
                //获取该IP对象的网关
                GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses;
                foreach (var gateWay in gateways)
                {
                    //如果能够Ping通网关
                    if (IsPingIP(gateWay.Address.ToString()))
                    {
                        //WriteLog("Gateway:" + gateWay.Address.ToString());
                        //得到网关地址
                        if (gateWay.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            if (!gateWay.Address.ToString().Contains("10"))
                            {
                                strGateway = gateWay.Address.ToString();
                                //WriteLog("realGateway:" + strGateway);
                                //跳出循环
                                break;
                            }
                        }
                         
                    }
                }

                //如果已经得到网关地址
                if (strGateway.Length > 0)
                {
                    //跳出循环
                    break;
                }
            }
            //返回网关地址
            return strGateway;
        }

 

你可能感兴趣的:(网络,网关,c#)