Solved

C# code to get IP address

Posted on 2014-10-03
4
2,053 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 40359556
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
ID: 40359566
Simple!
Yes.
So much for the 4 hours I have spent trying to do this this morning.
Thank you a lot.
0
 
LVL 34

Expert Comment

by:it_saige
ID: 40359630
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 34

Expert Comment

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

-saige-
0

Featured Post

Supports up to 4K resolution!

The VS192 2-Port 4K DisplayPort Splitter is perfect for anyone who needs to send one source of DisplayPort high definition video to two or four DisplayPort displays. The VS192 can split and also expand DisplayPort audio/video signal on two or four DisplayPort monitors.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Short answer to this question: there is no effective WiFi manager in iOS devices as seen in Windows WiFi or Macbook OSx WiFi management, but this article will try and provide some amicable solutions to better suite your needs.
Most of the applications these days are on Cloud. Cloud is ubiquitous with many service providers in the market. Since it has many benefits such as cost reduction, software updates, remote access, disaster recovery and much more.
If you're a developer or IT admin, you’re probably tasked with managing multiple websites, servers, applications, and levels of security on a daily basis. While this can be extremely time consuming, it can also be frustrating when systems aren't wor…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Suggested Courses
Course of the Month11 days, 18 hours left to enroll

623 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