0

I am implementing some code where I use a visitors IP address to determine their location. For .net core 2, this is:

var ipAddress = Request.HttpContext.Connection.RemoteIpAddress; 

But of course when I test locally I always get the loop back address ::1. Is there a way to simulate external IP addresses while testing locally?

2 Answers 2

1

You can create a service for retrieving remote address. Define an interface for it and create 2 implementations and inject them depending on the current environment

public interface IRemoteIpService { IPAddress GetRemoteIpAddress(); } public class RemoteIpService : IRemoteIpService { private readonly IHttpContextAccessor _httpContextAccessor; public RemoteIpService(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public IPAddress GetRemoteIpAddress() { return _httpContextAccessor.HttpContext.Connection.RemoteIpAddress; } } public class DummyRemoteIpService : IRemoteIpService { public IPAddress GetRemoteIpAddress() { //add your implementation return IPAddress.Parse("120.1.1.99"); } } 

Startup

if (HostingEnvironment.IsProduction()) { services.AddScoped<IRemoteIpService, RemoteIpService>(); } else { services.AddScoped<IRemoteIpService, DummyRemoteIpService>(); } 

Usage

public class TestController : Controller { //... private readonly IRemoteIpService _remoteIpService; public TestController(IRemoteIpService remoteIpService) { //... _remoteIpService = remoteIpService; } //.. [HttpGet] public IActionResult Test() { var ip = _remoteIpService.GetRemoteIpAddress(); return Json(ip.ToString()); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

For getting external ip for localhost, you need to send request to retrive the ip, and you could implement an extension for ConnectionInfo like

public static class ConnectionExtension { public static IPAddress RemotePublicIpAddress(this ConnectionInfo connection) { if (!IPAddress.IsLoopback(connection.RemoteIpAddress)) { return connection.RemoteIpAddress; } else { string externalip = new WebClient().DownloadString("http://icanhazip.com").Replace("\n",""); return IPAddress.Parse(externalip); } } } 

And use like

var ip = Request.HttpContext.Connection.RemotePublicIpAddress(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.