diff --git a/prometheus_client/exposition.py b/prometheus_client/exposition.py index 18233e24..551c708d 100644 --- a/prometheus_client/exposition.py +++ b/prometheus_client/exposition.py @@ -481,7 +481,16 @@ def _escape_grouping_key(k, v): def instance_ip_grouping_key(): """Grouping key with instance set to the IP Address of this host.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as s: - s.connect(('localhost', 0)) + if sys.platform == 'darwin': + # This check is done this way only on MacOS devices + # it is done this way because the localhost method does + # not work. + # This method was adapted from this StackOverflow answer: + # https://stackoverflow.com/a/28950776 + s.connect(('10.255.255.255', 1)) + else: + s.connect(('localhost', 0)) + return {'instance': s.getsockname()[0]} diff --git a/tests/test_exposition.py b/tests/test_exposition.py index a6c79ef0..7bb404b5 100644 --- a/tests/test_exposition.py +++ b/tests/test_exposition.py @@ -376,10 +376,6 @@ def my_redirect_handler(url, method, timeout, headers, data): # ensure the redirect took place at the expected redirect location. self.assertEqual(self.requests[1][0].path, "/" + self.redirect_flag) - @unittest.skipIf( - sys.platform == "darwin", - "instance_ip_grouping_key() does not work on macOS." - ) def test_instance_ip_grouping_key(self): self.assertTrue('' != instance_ip_grouping_key()['instance'])