Hashem Taheri
Hashem Taheri

Reputation: 45

How to get the ip of the user based on interaction with pod in K8s

I want to get the IP of the user(client) based on his interaction with the Pods, (I'm thinking about getting the user IP and locate him based on his IP)

I made the figure below for a better explanation of my question, the only thing I was able to find to maybe improve the situation was to patch the service and set externalTrafficPolicy to "Local" so the service will preserve the IP of the user.

But still not sure how or even at which part should I check the IP of the user. is it possible to monitor the activity of the user from outside of pod? any idea?

(I'm using golang)

k8s cluster with NodePort as a service

update: to make it more clear, i'm not creating the pods, in the scenario below clients are responsible and can create different pods and containers even the services they need, it's like a test-bed for them, so i cannot edit their containers file but i may be able to bring up another container beside their conatiner and then maybe use the answer at this post https://stackoverflow.com/a/27971761/9350055 to find the ip of the client. do you think this will work?

tiny container- two container in a single pod

Upvotes: 3

Views: 658

Answers (1)

Rico
Rico

Reputation: 61551

Sure, that will work but keep in mind that you will only receive traffic on the nodes where you have pods for the particular service (in your case Service NodePort).

If you are using Golang

Image1

Now, this should work with either L4 or L7 traffic. If you are using Golang an example of how to get it is looking at the X-Forwarded-For HTTP header:

package main

import (
    "encoding/json"
    "net/http"
)

func main() {
    http.HandleFunc("/", ExampleHandler)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    resp, _ := json.Marshal(map[string]string{
        "ip": GetIP(r),
    })
    w.Write(resp)
}

// GetIP gets a requests IP address by reading off the forwarded-for
// header (for proxies) and falls back to use the remote address.
func GetIP(r *http.Request) string {
    forwarded := r.Header.Get("X-FORWARDED-FOR")
    if forwarded != "" {
        return forwarded
    }
    return r.RemoteAddr
}

Also, here's an example of how to get for L4 services (TCP).

✌️

Upvotes: 1

Related Questions