Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C#
  4. Get IP address using c#

Get IP address using c#

Date- May 19,2023

Updated Jan 2026

8635

Free Download

Overview of IP Address Retrieval

An IP address (Internet Protocol address) is a unique identifier assigned to each device connected to a network. It serves two primary functions: identifying the host or network interface and providing the location of the device in the network. Whether you're developing a web application that needs to log user locations, or a network utility that requires device identification, knowing how to retrieve the IP address programmatically is essential.

In C#, the Dns class provides methods for obtaining the IP address of a device. This can be particularly useful for applications that require network diagnostics, such as identifying the source of a request or managing network configurations. Let's dive into how to implement this in your C# applications.

Prerequisites

Before you begin, ensure that you have the following:

  • A development environment set up for C# programming (e.g., Visual Studio).
  • Basic knowledge of C# and ASP.NET for web applications.
  • Access to a network where you can run tests to retrieve IP addresses.

Using the Dns Class to Retrieve IP Address

The Dns class in the System.Net namespace is the primary means of retrieving IP addresses. The example below demonstrates how to obtain the user's IP address in a web application:

using System;
using System.Net;
using System.Web.Mvc;

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var ipAddress = GetUserIpAddress();
        return View();
    }

    public string GetUserIpAddress(bool Lan = false)
    {
        string userIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (String.IsNullOrEmpty(userIPAddress))
            userIPAddress = Request.ServerVariables["REMOTE_ADDR"];
        if (string.IsNullOrEmpty(userIPAddress))
            userIPAddress = Request.UserHostAddress;

        if (string.IsNullOrEmpty(userIPAddress) || userIPAddress.Trim() == "::1")
        {
            Lan = true;
            userIPAddress = string.Empty;
        }

        if (Lan)
        {
            if (string.IsNullOrEmpty(userIPAddress))
            {
                string stringHostName = Dns.GetHostName();
                IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
                System.Net.IPAddress[] arrIpAddress = ipHostEntries.AddressList;
                try
                {
                    foreach (IPAddress ipAddress in arrIpAddress)
                    {
                        if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            userIPAddress = ipAddress.ToString();
                        }
                    }
                    if (string.IsNullOrEmpty(userIPAddress))
                        userIPAddress = arrIpAddress[arrIpAddress.Length - 1].ToString();
                }
                catch
                {
                    try
                    {
                        userIPAddress = arrIpAddress[0].ToString();
                    }
                    catch
                    {
                        try
                        {
                            arrIpAddress = Dns.GetHostAddresses(stringHostName);
                            userIPAddress = arrIpAddress[0].ToString();
                        }
                        catch
                        {
                            userIPAddress = "127.0.0.1";
                        }
                    }
                }
            }
        }
        return userIPAddress;
    }
}

In this example, we check various server variables to retrieve the user's IP address. If the address is not found, we fall back to local network checks.

Handling Local and Public IP Addresses

When developing applications, it's essential to understand the difference between local and public IP addresses. Local IP addresses are used within a private network, while public IP addresses are used on the internet. The code above handles both cases by checking for local addresses if the public address is not available.

For instance, if you're developing an application that needs to function both on a local network and over the internet, the method can be adapted to handle scenarios where users are accessing the application from different environments. Here is an example of how you could extend the existing code to differentiate between local and public IP addresses:

public string GetUserIpAddress(bool checkLocal = false)
{
    // existing code...

    if (checkLocal)
    {
        // Logic to handle local IP addresses
        // Similar to the existing checks
    }

    // return the resolved IP address
}

Common Edge Cases & Gotchas

When working with IP addresses, there are several edge cases and gotchas to be aware of:

  • Proxy Servers: Users behind a proxy may have their real IP address hidden. The HTTP_X_FORWARDED_FOR header is often used to retrieve the original IP but may not always be reliable.
  • IPv6 Support: Ensure your application can handle both IPv4 and IPv6 addresses. The example code currently focuses on IPv4.
  • Localhost: Accessing from localhost may return the loopback address (127.0.0.1). Always check for this condition to avoid confusion.

Performance & Best Practices

When retrieving IP addresses, consider the following best practices to ensure your application remains performant and reliable:

  • Cache Results: If you frequently query IP addresses, consider caching the results to minimize DNS lookups and enhance performance.
  • Exception Handling: Always implement robust exception handling to manage potential errors resulting from DNS failures or network issues.
  • Validate Input: If you're accepting IP addresses as input, validate them to prevent injection attacks or other security vulnerabilities.

Conclusion

In this blog post, we explored how to retrieve the IP address of a device using C# and the Dns class. We covered the nuances of local versus public IP addresses, handled common edge cases, and discussed best practices for performance and security.

  • Understand the difference between local and public IP addresses.
  • Implement robust exception handling and validation.
  • Consider caching results for improved performance.
  • Be aware of edge cases such as proxy servers and IPv6 compatibility.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Zoom C# Wrapper Integration
Jun 12, 2021
Convert HTML String To Image In C#
Jul 02, 2022
The report definition is not valid or is not supported by this version of reporting
Jul 02, 2022
Replacing Accent Characters with Alphabet Characters in CSharp
Jun 03, 2023
Previous in C#
How to Verify If base 64 string is valid for tiff image in C#
Next in C#
C# Regex Examples

Comments

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • How to Convert DataTable to List 7639 views
  • Asynchronous Programming in C# 7600 views
  • How to Verify If base 64 string is valid for tiff image in C… 7117 views
  • Compress image using ImageCompress NuGet package 6954 views
  • How to shuffle list in c# 6278 views
View all C# posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor