ASP.NET MVC : Get IP address of users - ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

ASP.NET MVC : Get IP address of users

In this article I am going to explain how to get IP address of users using mvc.

I want to get the IP address of visitors.

Add controller

Add an empty controller to project. Create an actionresult to get IP address.

Complete code of controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mvctest2017.Models;
using PagedList;
using System.IO;
using System.Text;
namespace mvctest2017.Controllers
    public class EmployeeController : Controller
        private DemoEntities db = new DemoEntities();

        // GET: /Employee/
        public ActionResult Index()
            return View();
        public ActionResult GetIPAddress()
            string ipaddress;
            ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ipaddress == "" || ipaddress == null)
            ipaddress = Request.ServerVariables["REMOTE_ADDR"];
            ViewBag.ipaddress = ipaddress;
            return View();

Add view

Add view for GetIPAddress action.

Complete source of view

    ViewBag.Title = "ASP.NET MVC : Get IP address of users";

IP address of user is : @ViewBag.ipaddress

*Note: This will show IP address ::1 when you run this on localhost but when you deploy the application and upload it on server, it will be work perfectly.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.