3

I am aware this question has been asked before. But in the ~8 years since, SignalR has changed rather a lot.

So does anyone know how to get the IP of a client from the SignalR hub?

I am using SignalR to communicate between two .net core applications on different servers, so there is no HTTP request or serving a website or anything like that.

1 Answers1

10

Inside your hub you can read IHttpConnectionFeature features like:

using Microsoft.AspNetCore.Http.Features;
...
var feature = Context.Features.Get<IHttpConnectionFeature>();

It will return an instance of IHttpConnectionFeature with the following properties:

public interface IHttpConnectionFeature
{
    //
    // Summary:
    //     The unique identifier for the connection the request was received on. This is
    //     primarily for diagnostic purposes.
    string ConnectionId { get; set; }
    //
    // Summary:
    //     The IPAddress of the client making the request. Note this may be for a proxy
    //     rather than the end user.
    IPAddress? RemoteIpAddress { get; set; }
    //
    // Summary:
    //     The local IPAddress on which the request was received.
    IPAddress? LocalIpAddress { get; set; }
    //
    // Summary:
    //     The remote port of the client making the request.
    int RemotePort { get; set; }
    //
    // Summary:
    //     The local port on which the request was received.
    int LocalPort { get; set; }
}

Code example:

public override Task OnConnectedAsync()
{
     var feature = Context.Features.Get<IHttpConnectionFeature>();
     _logger.LogInformation("Client connected with IP {RemoteIpAddress}", feature.RemoteIpAddress);
     return base.OnConnectedAsync();
}
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116