Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi frens


How can i find out the ipaddress , subnetmask and default gateway using c# windows form ?

I tried out some code to find ipaddress , its returning 127.0.0.1 which is correct , but i ve manually set the ip address to 198.168.1.2 ..How can i get that ?? Please give ur suggestions



Thanks in advance
Darshan
Posted
Comments
[no name] 5-Jul-13 10:51am    
http://social.msdn.microsoft.com/Forums/en-US/b7521e65-093f-4b87-8114-d1f6e311d86a/how-to-retrieve-subnet-mask-and-default-gateway-in-cnet-2005

1 solution

A machine can have zero or more network interfaces, IP addresses etc. The answer to your question is not a single answer but involves a list in each case.

To get the IP addresses and subnet mask for each interface:

C#
using System;
using System.Net.NetworkInformation;

public class blahblah
{
  public static void Main()
  {
    NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
    foreach(NetworkInterface Interface in Interfaces)
    {
      if(Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
      Console.WriteLine(Interface.Description);
      UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
      foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
      {
        Console.WriteLine("\tIP Address is {0}", UnicatIPInfo.Address);
        Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);
      }
    }
  }
}


To print the gateway:
C#
public void PrintDefaultGateway() 
{ 
   var defaultGateway = 
   from nics in NetworkInterface.GetAllNetworkInterfaces() 
   from props in nics.GetIPProperties().GatewayAddresses 
   where nics.OperationalStatus == OperationalStatus.Up 
   select props.Address.ToString(); 

   Console.WriteLine("\tGateway is {0}", defaultGateway.First());
}
 
Share this answer
 
Comments
Member 13350890 11-Apr-18 6:22am    
How can i get ip range from one subnet mask in c#?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900