From 56e4c4a067a303aa709e58fd5b253c259d96ce1a Mon Sep 17 00:00:00 2001
From: Manuel Franceschini <livewire@google.com>
Date: Wed, 30 Jun 2010 15:35:34 +0200
Subject: [PATCH] Enable utils.OwnIpAddress to work with IPv6 addresses

Currently a TcpPing using the target address as source is used to
determine wheter or not an IP address belongs to a node. This does not
work for IPv6 anymore (I'm not sure why) as binding to IPv6 localhost as
source for the TCP connection in TcpPing still results in a successful
connection, even in case the target address is non-local.

Signed-off-by: Manuel Franceschini <livewire@google.com>
Reviewed-by: Guido Trotter <ultrotter@google.com>
Reviewed-by: Iustin Pop <iustin@google.com>
---
 lib/utils.py | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/lib/utils.py b/lib/utils.py
index b32f041b2..f57cb8830 100644
--- a/lib/utils.py
+++ b/lib/utils.py
@@ -1794,8 +1794,8 @@ def TcpPing(target, port, timeout=10, live_port_needed=False, source=None):
 def OwnIpAddress(address):
   """Check if the current host has the the given IP address.
 
-  Currently this is done by TCP-pinging the address from the loopback
-  address.
+  This is done by trying to bind the given address. We return True if we
+  succeed or false if a socket.error is raised.
 
   @type address: string
   @param address: the address to check
@@ -1803,8 +1803,17 @@ def OwnIpAddress(address):
   @return: True if we own the address
 
   """
-  return TcpPing(address, constants.DEFAULT_NODED_PORT,
-                 source=constants.IP4_ADDRESS_LOCALHOST)
+  family = GetAddressFamily(address)
+  s = socket.socket(family, socket.SOCK_DGRAM)
+  success = False
+  try:
+    s.bind((address, 0))
+    success = True
+  except socket.error:
+    success = False
+  finally:
+    s.close()
+  return success
 
 
 def ListVisibleFiles(path):
-- 
GitLab