Solved

C# code to get IP address

Posted on 2014-10-03
4
1,627 Views
Last Modified: 2014-10-03
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

0
Comment
Question by:John Bolter
  • 2
4 Comments
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
 

Author Closing Comment

by:John Bolter
Comment Utility
Simple!
Yes.
So much for the 4 hours I have spent trying to do this this morning.
Thank you a lot.
0
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
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
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
Drat beaten by kaufmed.  And perhaps another phone call or two that took me away from this...  LOL

-saige-
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Preface There are many applications where some computing systems need have their system clocks running synchronized within a small margin and eventually need to be in sync with the global time. There are different solutions for this, i.e. the W3…
#Citrix #Citrix Netscaler #HTTP Compression #Load Balance
After creating this article (http://www.experts-exchange.com/articles/23699/Setup-Mikrotik-routers-with-OSPF.html), I decided to make a video (no audio) to show you how to configure the routers and run some trace routes and pings between the 7 sites…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now