C# code to get IP address

Hi, I have a simple query.

The gateway I am using for my internet connection is 10.0.0.1 as shown below.

I need C# code to return the IP given I know my gateway, ie. pass into my function 10.0.0.1 and return 10.0.0.14

There is code here that almost helps me http://stackoverflow.com/questions/13174909/get-ip-address-and-adapter-description-using-c-sharp

But I cannot get it to work.

Can someone help me out?

Thank you

John



C:\Users\johneb>ipconfig

Windows IP Configuration


Ethernet adapter Local Area Connection 5:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : bc1d::2851:9a0:a234:c82%26
   IPv4 Address. . . . . . . . . . . : 10.0.0.15
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.0.0.2

Ethernet adapter Local Area Connection 4:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : f190::d879:8fb:c9d8:e87%26
   IPv4 Address. . . . . . . . . . . : 10.0.0.14
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.0.0.1

Ethernet adapter Local Area Connection 3:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fa90::3591:cc2e:3555:558f%25
   Autoconfiguration IPv4 Address. . : 169.254.53.143
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :

Ethernet adapter Bluetooth Network Connection 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{EF7FEF35-AB01-42E8-9CD9-2FB2862617DD}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter Teredo Tunneling Pseudo-Interface:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{36933DFB-415E-43A4-AEBA-DCC6BDBA8A26}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter isatap.{5029C8B4-E74B-429E-A466-EFA6D5FB9905}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

C:\Users\johneb>
C:\Users\johneb>

Open in new window

John BolterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Does this do what you are after?

IPAddress gateway = IPAddress.Parse("10.0.0.1");
IPAddress myAddress = null;

foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
{
    var ipProps = adapter.GetIPProperties();

    foreach (GatewayIPAddressInformation gatewayInfo in ipProps.GatewayAddresses)
    {
        if (gatewayInfo.Address.Equals(gateway))
        {
            foreach (UnicastIPAddressInformation unicastInfo in ipProps.UnicastAddresses)
            {
                if (unicastInfo.Address.AddressFamily == AddressFamily.InterNetwork)
                {
                    myAddress = unicastInfo.Address;
                }
            }
        }
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
John BolterAuthor Commented:
Simple!
Yes.
So much for the 4 hours I have spent trying to do this this morning.
Thank you a lot.
0
it_saigeDeveloperCommented:
Try this:
using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace IPAddressExample
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine(Methods.GetIp("192.168.1.1"));
			Console.ReadLine();
		}
	}

	public static class Methods
	{
		/// <summary>Retrieves an IP address from the local addresslist of the instantiator</summary>
		public static IPAddress GetIp(string gateway = "")
		{
			IPAddress m_gateway = new IPAddress(0);
			return IPAddress.TryParse(gateway, out m_gateway) ? GetIp(m_gateway) : null;
		}

		/// <summary>Retrieves an IP address from the local addresslist of the instantiator</summary>
		public static IPAddress GetIp(IPAddress gateway = null)
		{
			try
			{
				var m_lprops = IPGlobalProperties.GetIPGlobalProperties();
				var m_address = new IPAddress(0);
				IPAddress m_gateway = new IPAddress(0);
				if (gateway != null)
					m_gateway = gateway;

				// If there are no local IP global properties, return a null value.
				if (m_lprops == null)
				{
					Console.WriteLine("There are no local ip global properties.");
					return null;
				}

				// If no network connection is available, return a null value.
				if (!NetworkInterface.GetIsNetworkAvailable())
				{
					Console.WriteLine("There are no active network connections available.");
					return null;
				}

				// If a network connection is available (marked as up and is not a loopback or tunnel interface), try to return the IPAddress object associated with the network connection.
				var m_adapters = NetworkInterface.GetAllNetworkInterfaces();

				// If there are no network connections, return a null value.
				if (m_adapters == null || m_adapters.Count() < 1)
				{
					Console.WriteLine("There are no network connections available.");
					return null;
				}

				foreach (var m_adapter in m_adapters)
				{
					// Filter to exclude network interfaces that are not up [it can transmit data packets].  If an adapter is excluded, fall out of the loop.
					if (m_adapter.OperationalStatus != OperationalStatus.Up)
					{
						Console.WriteLine(string.Format("{0} has an operational status of {1}.  This adapter will not be used.", m_adapter.Description, m_adapter.OperationalStatus));
						continue;
					}

					// Filter to exclude network interfaces that do not support Internet Protocol version 4.  If an adapter is excluded, fall out of the loop.
					if (!m_adapter.Supports(NetworkInterfaceComponent.IPv4))
					{
						Console.WriteLine(string.Format("{0} supports IPv4 - {1}.  This adapter will not be used.", m_adapter.Description, !m_adapter.Supports(NetworkInterfaceComponent.IPv4)));
						continue;
					}

					// Filter to exclude loopback network interfaces and unknown network interfaces.  If an adapter is excluded, fall out of the loop.
					if (m_adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback || m_adapter.NetworkInterfaceType == NetworkInterfaceType.Unknown)
					{
						Console.WriteLine(string.Format("{0} is a/an {1} type.  This adapter will not be used.", m_adapter.Description, m_adapter.NetworkInterfaceType));
						continue;
					}

					// Retrieve the properties of any adapters that meet the filter requirements.
					var m_props = m_adapter.GetIPProperties();

					// If there are no properties for this adapter, fall out of the loop.
					if (m_props == null)
					{
						Console.WriteLine(string.Format("There are no properties for adapter - {0}.  This adapter will not be used.", m_adapter.Description));
						continue;
					}

					// Filter to exclude network adapters that have no gateway address assigned to them.  If an adapter is excluded, fall out of the loop.
					if (m_props.GatewayAddresses.All(_gateway => _gateway.Address == new IPAddress(0)))
					{
						Console.WriteLine(string.Format("{0} has no gateway address(es) assigned - {1}.  This adapter will not be used.", m_adapter.Description, m_props.GatewayAddresses.All(_gateway => _gateway.Address == new IPAddress(0))));
						continue;
					}

					// Filter to exclude network adapters that have do not have a gateway address that matches the requested qateway, if any.  If an adapter is excluded, fall out of the loop.
					if (m_gateway != null && m_gateway != new IPAddress(0))
					{
						if (!m_props.GatewayAddresses.Any(_gateway => _gateway.Address.Equals(m_gateway)))
						{
							Console.WriteLine(string.Format("{0} has no gateway address(es) assigned that match -{1}.  This adapter will not be used.", m_adapter.Description, m_gateway));
							continue;
						}
					}

					// Retrieve the IPv4 properties of any adapters that meet the filter requirements
					var m_ipv4props = m_props.GetIPv4Properties();

					// Filter to exclude network adapters that have an automatice private addressing (APIPA) address assigned to them.  If an adapter is excluded, fall out of the loop.
					if (m_ipv4props.IsAutomaticPrivateAddressingActive)
					{
						Console.WriteLine(string.Format("{0} has an Automatic Private Addressing (APIPA) address assigned.  This adapter will not be used.", m_adapter.Description));
						continue;
					}

					// Retrieve the unicast addresses of any network adapters that meet the filter requirements.
					var m_unicastIPs = m_props.UnicastAddresses;

					// If there are no unicast ip addresses, fall out of the loop.
					if (m_unicastIPs == null)
					{
						Console.WriteLine(string.Format("{0} has no unicast address(es) assigned.  This adapter will not be used.", m_adapter.Description));
						continue;
					}

					foreach (var m_unicastIP in m_unicastIPs)
					{
						// Filter to exclude unicast addresses that do not have an IPv4 Subnet mask.  If a unicast address is excluded, fall out of the loop.
						if (m_unicastIP.IPv4Mask == null)
						{
							Console.WriteLine(string.Format("{0} has no IPv4 subnet mask.  This adapter will not be used.", m_adapter.Description));
							continue;
						}

						// Filter to exclude unicast addresses that are not valid and unrestricted.  If a unicast address is excluded, fall out of the loop.
						if (m_unicastIP.DuplicateAddressDetectionState != DuplicateAddressDetectionState.Preferred)
						{
							Console.WriteLine(string.Format("{0}'s duplicate detection state is {1}.  This adapter will not be used.", m_adapter.Description, m_unicastIP.DuplicateAddressDetectionState));
							continue;
						}

						//// Filter to exclude virtual netork addresses.  If a unicast address is excluded, fall out of the loop.
						//if (m_unicastIP.AddressPreferredLifetime == UInt32.MaxValue)
						//{
						//     Variables.FileLogger.RecordMessage(string.Format("Methods.GetIpAlternative: {0}'s unicast address {1} is a virtual address.  This adapter will not be used.", m_adapter.Description, m_unicastIP.Address), Log.MessageType.Informational);
						//     continue;
						//}

						// Filter to exclude addresses that are not IPv4 Addresses.  If a unicast address is excluded, fall out of the loop.
						if (m_unicastIP.Address.AddressFamily != AddressFamily.InterNetwork)
						{
							Console.WriteLine(string.Format("{0}'s unicast address {1} has an address family of {2}.  This adapter will not be used.", m_adapter.Description, m_unicastIP.Address, m_unicastIP.Address.AddressFamily));
							continue;
						}

						// Retrieve the IPAddress from the network interface.
						m_address = m_unicastIP.Address;

						Console.WriteLine(string.Format("Using adapter {0} with a unicast address of {1}.", m_adapter.Description, m_address));
					}

					if (BitConverter.ToUInt32(m_address.GetAddressBytes(), 0) != BitConverter.ToUInt32(new IPAddress(0).GetAddressBytes(), 0))
						break;
				}

				return BitConverter.ToUInt32(m_address.GetAddressBytes(), 0) == BitConverter.ToUInt32(new IPAddress(0).GetAddressBytes(), 0) ? null : m_address;
			}
			catch (NetworkInformationException ex)
			{
				// A windows system function call failed.
				Console.Write(string.Format("Network Information Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message));
				return null;
			}
			catch (PlatformNotSupportedException ex)
			{
				// This property is not valid on computers running operating systems earlier than Windows XP.
				Console.WriteLine(string.Format("Platform Not Supported Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message));
				return null;
			}
			catch (Exception ex)
			{
				// Generic exception.
				Console.WriteLine(string.Format("Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message));
				return null;
			}
		}
	}
}

Open in new window


Produces this output:Capture.JPG
-saige-
0
it_saigeDeveloperCommented:
Drat beaten by kaufmed.  And perhaps another phone call or two that took me away from this...  LOL

-saige-
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.