The function below retrieves the IP address of a local machine using C#. This sample code uses the system.NET namespace to get the host name and then gets the IP address for that host name.

C#

        private string GetIPAddress()
        {

            StringBuilder sb = new StringBuilder();
            String strHostName = string.Empty;
            strHostName = Dns.GetHostName();
            sb.Append("The Local Machine Host Name: " + strHostName);
            sb.AppendLine();

            IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] address = ipHostEntry.AddressList;

            sb.Append("The Local IP Address: " + address[4].ToString());
            sb.AppendLine();

            return sb.ToString();

        }

Now let’s call this function from a Form Load Event:

C#:

        private void frm_Load(object sender, EventArgs e)
        {
            try
            {
                MessageBox.Show(GetIPAddress());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

The output:

Related Article:

 

Last modified: March 6, 2019

Comments

Write a Reply or Comment

Your email address will not be published.