Introduction
Some time it is required to capture client's IP address when a client makes call to the service, this blog contains code snippet that describes how to get client's IP address in WCF service when a client makes call to the service. Below code snippet contains full code to get the client's IP address.
Getting Started
There may have many way to get IP Address of client when client calls to service. Here this code snippet 4 steps to get the IP Address of client. In First step when your WCF Client calls to the service(lets say client called a function of your service), create object of your service with the help of OperationContext class.
Second get incoming message property details from current context of service which contains the endpoint details of client and get the message endpoint (client endpoint) details from message property. finally from message endpoint retrieve the IP Address of client. see the below code contains the code details what we have discussed.
// creating object of service when request comes
OperationContext context = OperationContext.Current;
//Getting Incoming Message details
MessageProperties prop = context.IncomingMessageProperties;
//Getting client endpoint details from message header
RemoteEndpointMessageProperty endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
var ip= endpoint.Address;
Code for Getting Client's IP Address in WCF Service
The first code creates the current instance of service by using Current property of OperationContext class. The second code retrieves the instance of incoming message of the service and the third code gets the endpoint details from incoming message that contains client details like ip address.
Finally, the last code retrieved the IP Address from the endpoint.
Related Articles
- Difference Between DataContractSerializer and XMLSerializer
- Consuming Restful API with Bearer Token Authentication using HttpWebRequest
- WCF Bindings
- Concurrency Mode In WCF
Summary
In the blog we have discussed how to retrieve IP Address of client, when a client makes call to WCF service, hope you have understood better and this blog makes help full to you.
Thanks