How can we get the first IP4 Address of the local machine in c#?

When we write client server or peer to peer application, a frequent task is to find the first IP4 address of local machine. A machine has multiple types of addresses besides IP4 and IP6. For this reason, we will first get the address list of the machine then will loop through all the addresses to check whether there is an IP4 address. If found then we will return the first address. Otherwise will  return null.

Now the question is how we will detect IP4 address Type. There is an Enumeration named AddressFamily under System.Net.Sockets namespace which specifies the addressing type. The members of AddressFamily Enumeration are in the following:

Member name 

Description

Unknown

Unknown address family.

Unspecified

Unspecified address family.

Unix

Unix local to host address.

InterNetwork

Address for IP version 4.

ImpLink

ARPANET IMP address.

Pup

Address for PUP protocols.

Chaos

Address for MIT CHAOS protocols.

NS

Address for Xerox NS protocols.

Ipx

IPX or SPX address.

Iso

Address for ISO protocols.

Osi

Address for OSI protocols.

Ecma

European Computer Manufacturers Association (ECMA) address.

DataKit

Address for Datakit protocols.

Ccitt

Addresses for CCITT protocols, such as X.25.

Sna

IBM SNA address.

DecNet

DECnet address.

DataLink

Direct data-link interface address.

Lat

LAT address.

HyperChannel

NSC Hyperchannel address.

AppleTalk

AppleTalk address.

NetBios

NetBios address.

VoiceView

VoiceView address.

FireFox

FireFox address.

Banyan

Banyan address.

Atm

Native ATM services address.

InterNetworkV6

Address for IP version 6.

Cluster

Address for Microsoft cluster products.

Ieee12844

IEEE 1284.4 workgroup address.

Irda

IrDA address.

NetworkDesigners

Address for Network Designers OSI gateway-enabled protocols.

Max

MAX address.

(The table is stolen from MSDN website)

 The member InterNetwork  of AddressFamily Enumeration indicates Address for IP version 4.Here the member InterNetwork  of AddressFamily Enumeration  is used to check whether this is a IP4 address or not. The routine to find the first IP4 Address of the Host (local) machine is in the following:

   1: private static IPAddress ReturnMachineIP()
   2:    {
   3:        String hostName = Dns.GetHostName();
   4:        IPHostEntry ipEntry = Dns.GetHostEntry(hostName);
   5:        IPAddress[] addr = ipEntry.AddressList;
   6:        IPAddress ipV4 = null;
   7:        foreach (IPAddress item in addr)
   8:        {
   9:            if (item.AddressFamily == AddressFamily.InterNetwork)
  10:            {
  11:                ipV4 = item;
  12:                break;
  13:            }
  14:  
  15:        }
  16:        if (ipV4 == null)
  17:        {
  18:            throw new ApplicationException("You have no IP of Version 4.Server can not run witout it");
  19:        }
  20:        return ipV4;
  21:    }

   Hope this will save some of your time.

No Comments