Good Afternoon,

I'm new to C# programming and I'm taking Networking this semester. The professor asks to write a program in C# Write a program to discover the IP address of your machine. Also an interesting modification to this program is to give the host name and let the program printout the IP address. So far I have this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Web;

namespace COMPUTER_IPADDRESS_FINDER
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        

        private void btnCheckIP_Click(object sender, EventArgs e)
        {
            try
            {
                IPHostEntry hostname = Dns.GetHostEntry(txthostname.Text );
                IPAddress[] ip = hostname.AddressList;
                txtIpAddress.Text = ip[0].ToString();
                txthostname.Text = Dns.GetHostName();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

In advance thank you for your cooperation.

Thank you

Dani AI

Generated

Short primer: there are two related tasks here — list the IP addresses assigned to your machine (local/private addresses) and resolve an arbitrary hostname to its IP(s). The thread already shows the common starting points: uses a DNS lookup, and pick a single entry from AddressList, gives the most robust NIC-based enumeration, and correctly points out that your external/public IP is discoverable only by asking an external service.

Practical tips and pitfalls to watch for:

  • Never assume AddressList[0] or AddressList[last] is the “right” address — it may be loopback, IPv6, or an APIPA (169.254.x.x) address. Always check array length and filter by AddressFamily (use AddressFamily.InterNetwork for IPv4) and skip loopback/APIPA entries.
  • If your hostname textbox can be empty, resolve a host variable first rather than calling DNS with an empty string; that prevents unnecessary exceptions.
  • Dns.Resolve is obsolete — prefer Dns.GetHostEntry or Dns.GetHostAddresses.
  • To enumerate every useful address and show where it came from (adapter name, type, operational state), use the NetworkInterface + IPInterfaceProperties.UnicastAddresses approach (as suggested). That method tells you which adapter the address belongs to and whether the interface is Up.

A simple, safe hostname-resolution pattern (filtering for IPv4 and skipping loopback/APIPA):

var host = string.IsNullOrWhiteSpace(txthostname.Text) ? Dns.GetHostName() : txthostname.Text;
var addrs = Dns.GetHostAddresses(host)
    .Where(a => a.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(a) && !a.ToString().StartsWith("169.254"))
    .ToArray();
if (addrs.Length > 0) txtIpAddress.Text = addrs[0].ToString();
else txtIpAddress.Text = "No usable IPv4 address found";

If you need the public/external IP (what the Internet sees), it must be fetched from an external web service (simple HTTP GET to a “what is my IP” endpoint) — this is separate from local lookups and will reflect any NAT or carrier-grade address your router provides. Finally, show all addresses in the UI rather than one — it helps when a machine has multiple NICs, VPNs, or IPv6 enabled.

Recommended Answers

All 5 Replies

Hi..

This would help you to retrive ip of the system.

private void button4_Click(object sender, EventArgs e)
        {
           // string hostname = System.Net.Dns.GetHostName();
            string strHostName = "";
            strHostName = System.Net.Dns.GetHostName();

            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

            IPAddress[] addr = ipEntry.AddressList;

            MessageBox.Show(addr[addr.Length - 1].ToString());
}

Also have a look at this.
Use a MessageBow, Label or TextBox to show the strings, intead of WriteString.

Even you can try this method also.

private void btnCheckIP_Click(object sender, EventArgs e)
{
try
{
            string HostName = System.Net.Dns.GetHostName().ToString();
            string UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
            UserName = UserName.Replace(@"\", @"\\");
            string IPAddresses = "";
            System.Net.IPHostEntry _IPHostEntry = System.Net.Dns.Resolve(HostName);
            foreach (System.Net.IPAddress IPAddress in _IPHostEntry.AddressList)
            {
                IPAddresses += IPAddress.ToString() + ";";
            }
           MessagBox.Show(HostName + "~,~" + UserName + "~,~" + IPAddresses.Trim());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

Are you looking for the internal, or the external IP (or both)? It is not very trivial to figuire out your external IP (the one the rest of the world uses to talk to you, not the one assigned to you by a NAT router) - in fact the only way I know of to do it programatically is to fetch the http sent by a site like www.whatsmyip.com.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace SerialTester
{
  class NetworkHelper
  {
    static NetworkInterface[] GetAllNetworkInterfacesSafe()
    {
      try
      {
        return
          NetworkInterface.GetAllNetworkInterfaces()
          .Where(nic => (nic.IsReceiveOnly == false) && (nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) && (nic.OperationalStatus == OperationalStatus.Up))
          .ToArray();
      }
      catch (Exception ex)
      {
        //log4net if (log.IsErrorEnabled) log.Error("Error retrieving network interfaces", ex);
        return new NetworkInterface[0];
      }
    }
    public static IEnumerable<UnicastIPAddressInformation> GetAllUnicastIPAddressInformation(AddressFamily family)
    {
      if (!Enum.IsDefined(typeof(AddressFamily), family))
        throw new System.ComponentModel.InvalidEnumArgumentException("family", (int)family, typeof(AddressFamily));
      NetworkInterface[] interfaces = GetAllNetworkInterfacesSafe();
      for (int i1 = 0; i1 < interfaces.Length; i1++)
      {
        IPInterfaceProperties props;
        try
        {
          props = interfaces[i1].GetIPProperties();
        }
        catch (Exception ex)
        {
          //log4net if (log.IsErrorEnabled) log.Error("Error retrieving IP properties", ex);
          continue;
        }

        for (int i2 = 0; i2 < props.UnicastAddresses.Count; i2++)
        {
          if ((props.UnicastAddresses[i2].Address != null) && (props.UnicastAddresses[i2].Address.AddressFamily == family))
            yield return props.UnicastAddresses[i2];
        }
      }
    }
  }
}

Calling:

void button3_Click(object sender, EventArgs e)
    {
      System.Net.NetworkInformation.UnicastIPAddressInformation[] ips = NetworkHelper.GetAllUnicastIPAddressInformation(System.Net.Sockets.AddressFamily.InterNetwork).ToArray();
      for (int i1 = 0; i1 < ips.Length; i1++)
      {
        System.Diagnostics.Debug.WriteLine(ips[i1].Address);
      }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.