| |
| from __future__ import absolute_import, division, print_function, unicode_literals |
|
|
| import os |
| import socket |
|
|
| from .callcache import callcache |
|
|
|
|
| @callcache |
| def get_local_ip(): |
| """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: |
| |
| 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(): |
| """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: |
| |
| 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(): |
| """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: |
| |
| s.connect(('2001:4860:4860::8888', 80)) |
| ipv6 = s.getsockname()[0] |
| except Exception: |
| ipv6 = '::1' |
| finally: |
| s.close() |
| return ipv6 |
|
|