jak pobrac adres IP, który zostanie uzyty przez IIS lub UseUrl (.net 6)

0

czesc, zaczalem uzywac w projekcie signalR (serwer i client) w którym muszę okreslić adres ip na który rozsyłam różne message
problem jest taki, ze jak odpalimy apke dotnet ... --Urls ("adres_ip")
to wtedy po localhoscie juz nie pojdzie
taka sama sytuacja, gdy hostujemy na IIS i tam sobie damy binding pod konkretny adres IP

W jaki sposób moge pobrać adres IP na którym aktualnie pracuje apka (czy to przez kestrel, czy to przez IIS) ?
Jak coś, to mam dostep do IServiceCollection, IConfiguration, itd.

Nie chciałbym na sztywno ustawiać adresu IP w appsettingsach, bo każdy klient(osoba, nie apka) może sobie bindować inaczej

1

Zawsze możesz odpytać jakiś serwer o to :P

curl -s 'http://checkip.dyndns.org'
<html><head><title>Current IP Check</title></head><body>Current IP Address: 123.123.123.123</body></html>

albo

curl -s 'https://icanhazip.com/'

zwracający samo

123.123.123.123

;)

chociaż to w sumie trochę security issue mogłoby być :D

0

Może IServerAddressesFeature? Nie wiem jak to się zachowa w przypadku IIS.

0

w iis moge chyba wykorzystac libke (costam managamenet) i pobrac aktualna apke i jej wszystkie adresy ip ale co jak ktos se postawi recznie przez kestrela, na azurze, czy jakkolwiek ;D

0

to pobiera adres ip maszynki, ale mozna serwer skonfigurowac, aby mial inne ip - tu jest caly problem :P

0

Znalazłem taki urywek kodu:

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ExtensionClass
/// </summary>
public static class ExtensionClass
{
  /// <summary>
  /// Returns the <see cref="HttpContextBase"/> for this <see cref="IRequest"/>.
  /// </summary>
  /// <param name="request">The request</param>
  public static HttpContextBase GetHttpContext(this IRequest request)
  {
    object httpContextBaseValue;
    if (request.Environment.TryGetValue(typeof(HttpContextBase).FullName, out httpContextBaseValue))
    {
      return httpContextBaseValue as HttpContextBase;
    }
    return null;
  }
  public static string GetRemoteIpAddress(this IRequest request)
  {
    object ipAddress;
    //server.LocalIpAddress
    if (request.Environment.TryGetValue("server.RemoteIpAddress", out ipAddress))
    {
      return ipAddress as string;
    }
    return "";
  }
}
public override Task OnConnected()
{
  string ClientReferrerURL = Context.Request.GetHttpContext().Request.ServerVariables["HTTP_REFERER"];
  string RemoteIpAddress = Context.Request.GetRemoteIpAddress();
   
  return base.OnConnected();
}

Może będzie pomocne

0

to powyższe też nie zadziała, bo tutaj nie ma żadnego requesta, tu jest background task, który śledzi zmiany na innym api,
w razie gdy zauważy, wykonuje pewne operacje i używając klienta signalR, wysyła info do serwera signalR, który następnie wysyła na podstawie tego info do wszystkich podłączonych klientów :(

2

ok, skoro to jest BackgroundService to nie ma oczywiście HttpContext. Może spróbuj w ten sposób?

using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    private readonly IServer server;

    public HomeController(IServer server)
    {
        this.server = server;
    }

    public IActionResult Index()
    {
        var addresses = server.Features.Get<IServerAddressesFeature>().Addresses;
        Console.WriteLine($"Addresses from HomeController.Index: {string.Join(", ", addresses)}");
        return View();
    }
}

To przykład z kontrolerem, ale można to wstrzyknąć do innego serwisu
Źródło: https://swimburger.net/blog/dotnet/how-to-get-aspdotnet-core-server-urls

Edit: Sprawdziłem, u mnie działa:

builder.Services.AddHostedService<TimedHostedService>();
public class TimedHostedService : IHostedService, IDisposable
{
    private readonly ILogger<TimedHostedService> _logger;
    private System.Threading.Timer? _timer = null;
    private readonly IServer _server;

    public TimedHostedService(ILogger<TimedHostedService> logger, IServer server)
    {
        _logger = logger;
        _server = server;
    }

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service running.");

        _timer = new System.Threading.Timer(DoWork, null, TimeSpan.Zero,
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object? state)
    {
        var addresses = _server.Features.Get<IServerAddressesFeature>().Addresses;
        _logger.LogInformation($"Addresses: {string.Join(", ", addresses)}");
    }

    public Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}
TimedHostedService: Information: Addresses: https://localhost:7246, http://localhost:5164
TimedHostedService: Information: Addresses: https://localhost:7246, http://localhost:5164
TimedHostedService: Information: Addresses: https://localhost:7246, http://localhost:5164
0

super, dzieki, o to mi chodzilo!
wrzucam to do metody configure w startup i mam wszystkie adresy na ktoryh apka nasłuchuje :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1