Search code examples
c#wcfipcnettcpbinding

Using C# NetTCPBinding and WCF, How Do I Get the Port the Client is Connecting From for Same Machine TCP Communication?


I'm trying to find out what C# method, or attribute on some known variable, I can use to determine information about the client. The communication is happening fine. I'm using NetTCPBinding and have specified a port of, let's say, 9000. My understanding of TCP connections is that this is the listening port, but the communication from the client would happen on another port.

Right now, I'm looking inside the server's method from when the client called it and probing the OperationContext.Current for any information that might show where the message came. I do see another port number under OperationContext.Current.Channel.ListenUri.Syntax.m_Port as 808. I read from this link https://superuser.com/questions/1159747/windows-advanced-firewall-why-is-port-808-open-by-default that this is a Port Sharing port from Microsoft. So, is this the port the communication is happening? If not, how do I go about getting the actual port the communication happens?

(The larger reason for this is I'm trying to perform hardening and ensure only valid clients - which will always be same machine - are connecting to this server.)


Solution

  • Makes available the client IP address and port number associated with the remote endpoint from which a message was sent.

    Here is the sample code.

    RemoteEndpointMessageProperty remoteEndpoint = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
    
    if (remoteEndpoint != null)
    {
        string clientIPAddress = remoteEndpoint.Address; 
        int clientPort = remoteEndpoint.Port; 
    }
    else
    {
        Console.WriteLine("Can't get info from remote endpoint");
    }
    return string.Format("You entered: {0}", value);