C#獲取網關的對應的局域網IP

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace MyNet
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine(String.Format("{0}", GetGatewayIp()));

        }

        public static string GetGatewayIp()
        {
            string gateway = DefaultGateway();

            string[] gatewayArr = gateway.Split('.');

            string gatewayNum = "";

            try
            {
                gatewayNum = gatewayArr[gatewayArr.Length - 2];
            }
            catch
            {

            }

            string ip = "";

            if (gatewayNum == "")
                return ip;

            string hostName = Dns.GetHostName();

            IPAddress[] list = Dns.GetHostEntry(hostName).AddressList;

            foreach (var _list in list)
            {
                if (_list.AddressFamily == AddressFamily.InterNetwork)
                {
                    string[] ipArr = _list.MapToIPv4().ToString().Split('.');

                    try
                    {
                        if (ipArr[ipArr.Length - 2] == gatewayNum)
                            ip = _list.MapToIPv4().ToString();
                    }
                    catch { }

                }
            }

            return ip;
        }

        public static string DefaultGateway()
        {
            string gateway = "";
            NetworkInterface[] networkInterface = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var network in networkInterface)
            {
                var ip = network.GetIPProperties();
                var addr = ip.GatewayAddresses;
                foreach (var gw in addr)
                {
                    Ping ping = new Ping();
                    try
                    {
                        PingReply pingRs = ping.Send(gw.Address, 100);
                        gateway = gw.Address.ToString();
                        break;
                    }
                    catch
                    {

                    }
                }
                if (gateway != "")
                    break;
            }
            return gateway;
        }

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章