<p>Giving the port forward object</p>
<pre><code>from kubernetes.stream import stream, portforward


    pf = portforward(
         k8s_client_v1.connect_get_namespaced_pod_portforward,
         pod_name,
         name_space,
         ports=port
    )
    
    pf.socket(port)
</code></pre>
<p><code>pf</code> is a socket object from <code>AF_UNIX</code> family.</p>
<p>I need a better understating whether another <code>AF_INET</code> family socket has to be instantiated in oder to achieve the same functionality as <code>kubectl</code> client has, ex: <code>kubectl port-forward $pod_name $port</code></p>
<p>I appreciate in advance if someone could share any snippets of this type of implementation.</p>
<p>At this moment creating port forward object was inspired from <a href="https://github.com/kubernetes-client/python/blob/master/examples/pod_portforward.py#L176" rel="nofollow noreferrer">here</a></p>

<p>Thanks to your code snipped, I could get this to work for me - which means that your code basically works: I have successfully used it to send TCP data on a custom port to a kubernetes services (haven't tried UDP, though). It seems to work quite similar but not exactly the same as <code>kubectl port-forward</code>.</p>
<p>The main difference is that it doesn't actually open an <code>AF_INET</code> socket on your system, but an <code>AF_UNIX</code> socket, which means, that it basically is addressed via a file name instead of a tuple of an IP address and port number. So it really depends on what you try to achieve.</p>
<p>If you just want to write to a socket from a Python script that is connected to a specific port of a service: This is the solution. It doesn't really make a difference for you that the kubernetes API provides you an <code>AF_UNIX</code> socket.</p>
<p>However, if you want to open a local port that connects to the kubernetes service port (e.g. use local tools to connect to a kubernetes service like a CLI based database management tool), this is only half of what you want to achieve. After some time playing around, including trying hacks like <code>socket.fromfd(unix_sock.fileno(), socket.AF_INET, socket.SOCK_STREAM)</code>, I came to the conclusion that a straight forward approach to &quot;convert&quot; the unix socket to a internet socket isn't possible.</p>
<p>A solution, I would suggest is to implement a simple port forwarding in Python. That would mean running a thread that opens an internet socket on the local port you'd like to use, receive data on that and simply forward it to the unix socket. It doesn't feel very elegant and probably isn't very efficient, either, but it should do the job.</p>
<p>Another alternative would be using an external tool like <code>socat</code> if available to connect the two sockets.</p>
