Get the IP Address of a local machine Using C#

Tutorials PanelPosted by

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:

Create a Simple Thread Program Using C#

Create system tray icon in windows forms application using C# and VB.Net

Socket connect and data send using C#

 

Leave a Reply

Your email address will not be published. Required fields are marked *