Gateway IP from Machine IP

21:39

Introduction

In this article I show how to get Gateway IP from Machine IP

Create Simple Application

Go to Visual Studio > File > New > Project > Windows > Console Application
Create a class name Route.cs and replace by below class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetGatewayIPFromMachineIP
{
    public class Route
    {
        private uint _address;
        private uint _mask;
        private string _gateway;
        private uint _interface;
        private int _metric;
        public uint Address { get { return this._address; } }
        public uint Mask { get { return this._mask; } }
        public uint Interface { get { return this._interface; } }
        public string ReadableAddress { get { return Route.IPLongToString(this._address); } }
        public string ReadableMask { get { return Route.IPLongToString(this._mask); } }
        public string ReadableInterface { get { return Route.IPLongToString(this._interface); } }
        public string Gateway { get { return (this._gateway); } }

        public Route(string[] route)
        {
            this._address = IPStringToLong(route[0]);
            this._mask = IPStringToLong(route[1]);
            this._gateway = route[2].ToString();
            this._interface = IPStringToLong(route[3]);
            this._metric = UInt16.Parse(route[4]);
        }

        public Route(string line) : this(line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) { }

        public static uint IPStringToLong(string str)
        {
            string[] values = str.Split(new char[] { '.' });
            uint multiplier = 1;
            uint value = 0;
            for (int i = 3; i >= 0; i--)
            {
                value += UInt32.Parse(values[i]) * multiplier;
                multiplier *= 256;
            }
            return value;
        }

        public static string IPLongToString(uint addr)
        {
            byte[] bytes = BitConverter.GetBytes(addr);
            string[] bs = new string[] { "", "", "", "" };

            for (int i = 0; i < 4; i++)
            {
                bs[i] = bytes[3 - i].ToString();
            }
            return String.Join(".", bs);
        }
    }
}
Now replace the Program.cs code by below code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace GetGatewayIPFromMachineIP
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Please enter machine IP:");
                var IP = Console.ReadLine();
                var GatewayIP = getGatewayIP(IP);
                Console.WriteLine("Your Machine IP: " + IP);
                Console.WriteLine("Your Gateway IP: " + GatewayIP);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

        public static string getGatewayIP(string IP)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = false;
            p.StartInfo.FileName = "route";
            p.StartInfo.Arguments = "PRINT " + IP;
            p.Start();
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
            p.Dispose();

            string[] lines = output.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            List<Route> routes = new List<Route>();
            bool found = false;
            foreach (string line in lines)
            {
                if (line == "Active Routes:")
                {
                    if (found)
                        break;
                    found = true;
                    continue;
                }

                if (found)
                {
                    if (line[0] == 'N')
                        continue;
                    else if (line[0] == '=')
                        break;
                    routes.Add(new Route(line));
                }
            }
            routes.Sort();
            return routes[0].Gateway.ToString();
        }
    }
}
Run the application and we can see the below screen:


Download

You can download application zip file here - 41.2 KB

Conclusion

It is very easy process to get a Gateway IP from Machine IP :)

You Might Also Like

0 comments