When you access an application by using Server Load Balancer (SLB), you can use the following method to obtain the IP address of the client from the code.

Issue

After I create an application in EDAS and bind it to an SLB instance, a client accesses the application by using the SLB instance. How can I obtain the real IP address of the client from Java code in the backend?

Note You can also check the client IP from the SLB (Intranet) and SLB (Internet) parameter on the Basic Information > Application Settings page.

Solution

The solution can vary depending on the type of cluster where the application is deployed.

  • Applications that are deployed in an Elastic Compute Service (ECS) cluster

    You can run the following command to obtain the client IP address from the Java code in the backend:

    String client_ip = request.getHeader("x-forwarded-for");                

    You can also obtain the real IP address of the client by getting the x-real-ip and wl-proxy-client-ip parameters from the HTTP header.

  • Applications that are deployed in a Container Service Kubernetes cluster

    1. Log on to the Container Service for Kubernetes console. Click Cluster. Then, find the Kubernetes cluster that you created and click Dashboard in the Actions column.
    2. In the left-side navigation pane, click Services. On the Services page, click the application that is deployed by using the EDAS console.
    3. On the page that appears, click Edit in the upper-right corner of the page.
    4. In the Edit Service dialog box, set the externalTrafficPolicy parameter from the default Cluster to Local. Then, click UPDATE. The service configurations are dynamically updated.
    5. You can run the following command to obtain the real IP address of the client from the Java code in the backend:
      String client_ip = request.getRemoteAddr();              

    You can transform the preceding methods for the applications that are deployed in an ECS cluster and the applications that are deployed in a Container Service for Kubernetes cluster. You can use the ternary operator to convert these two methods into a line of code:

    String client_ip = request.getHeader("x-forwarded-for") == null ? request.getRemoteAddr() : request.getHeader("x-forwarded-for");               

    This way, you can combine the two methods into one method that can are suitable for different types of clusters in EDAS.

    In addition, to modify the externalTrafficPolicy parameter, you can run the following kubectl command:

    Note You can use the preceding method only after you configure the KubeConfig file in the Connect to a Kubernetes cluster using kubectl section on the Cluster Information page.
    kubectl patch svc <service_name> -p '{"spec":{"externalTrafficPolicy":"Local"}}'