Code-Sharp / WampSharp

A C# implementation of WAMP (The Web Application Messaging Protocol)
http://wampsharp.net
Other
385 stars 84 forks source link

How do I get the IP of a client in the session created event on the router? #354

Closed LogicalFailure closed 1 year ago

LogicalFailure commented 1 year ago

Hi I would like to get the IP address of a client in the session created event on the router for logging purposes how would I go about this?

Please consider the following code (I want to access the clients IP address in the parts where it logs their session ID):

using WampSharp.V2;
using WampSharp.V2.Realm;

internal class Program
{
    private static async Task Main(string[] args)
    {
        const string location = "ws://127.0.0.1:8080/ws";
        using (IWampHost host = new DefaultWampHost(location))
        {
            IWampHostedRealm realm = host.RealmContainer.GetRealmByName("realm1");

            host.Open();

            Console.WriteLine("Server is running on " + location);
            Console.ReadLine();
        }
    }

    private static void OnSessionCreated(object? sender, WampSessionCreatedEventArgs e)
    {
        Console.WriteLine(e.SessionId);
    }

    private static void OnSessionClosed(object? sender, WampSessionCloseEventArgs e)
    {
        Console.WriteLine(e.SessionId);
    }
}
darkl commented 1 year ago

This property exists, but unfortunately the type that is holding it is internal, so you will have to use reflection.

private static void OnSessionCreated(object? sender, WampSessionCreatedEventArgs e)
{
    Console.WriteLine(e.SessionId);
    WampTransportDetails transportDetails = e.HelloDetails.TransportDetails;
    PropertyInfo peerProperty = transportDetails.GetType().GetProperty("Peer");
    object? peerValue = peerProperty.GetValue(transportDetails);
    Console.WriteLine(peerValue);
}
LogicalFailure commented 1 year ago

Thanks that worked :)