File size: 2,321 Bytes
f31fe4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals

import os
import socket

from .callcache import callcache


@callcache
def get_local_ip():  # type: () -> str
    """Get current machine's primary IP. If called in a TCE container, host IP will returned.

    Notice that this function is not reliable for which outgoing IP will used exactly, so this function should be used
    for metrics information.

    :returns: Host IP
    :rtype: str
    """
    ipv4 = os.environ.get('MY_HOST_IP')
    ipv6 = os.environ.get('MY_HOST_IPV6')

    if ipv4:
        return ipv4
    if ipv6:
        return ipv6

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        ip = s.getsockname()[0]
    except Exception:
        ip = '127.0.0.1'
    finally:
        s.close()
    return ip


@callcache
def get_local_ipv4():  # type: () -> str
    """Get current machine's primary IPv4. If called in a TCE container, host IP will returned.

    Notice that this function is not reliable for which outgoing IP will used exactly, so this function should be used
    for metrics information.

    :returns: Host IP
    :rtype: str
    """
    ip = os.environ.get('MY_HOST_IP')

    if ip:
        return ip

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        ip = s.getsockname()[0]
    except Exception:
        ip = '127.0.0.1'
    finally:
        s.close()
    return ip


@callcache
def get_local_ipv6():  # type: () -> str
    """Get current machine's primary IPv6. If called in a TCE container, host IP will returned.

    Notice that this function is not reliable for which outgoing IP will used exactly, so this function should be used
    for metrics information.

    :returns: Host IP
    :rtype: str
    """
    ipv6 = os.environ.get('MY_HOST_IPV6')

    if ipv6:
        return ipv6

    s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('2001:4860:4860::8888', 80))
        ipv6 = s.getsockname()[0]
    except Exception:
        ipv6 = '::1'
    finally:
        s.close()
    return ipv6