@@ -348,27 +348,47 @@ def to_dict(self):
348348 return fields
349349
350350
351- def get_public_ip (self ):
352- """Returns a server's public IP. Prioritizes IPv4 over IPv6."""
351+ def get_public_ip (self , addr_family = 'IPv4' , strict = False ):
352+ """
353+ Returns a server's public IP.
354+
355+ Params:
356+ - addr_family: prefer IPv4 (default) or IPv6.
357+ - strict mode (false/off by default): only return IP if it belongs to addr_family (IPv4 or IPv6).
358+
359+ Tries to fetch Server data from API if ip_addresses not set.
360+
361+ New in 3.4:
362+ - possibility to specify which protocol is preferred via addr_family,
363+ instead of always preferring IPv4.
364+ - strict mode
365+ """
366+
367+ if addr_family not in ['IPv4' , 'IPv6' ]:
368+ raise Exception ("`addr_family` must be 'IPv4' or 'IPv6'" )
353369
354370 if not hasattr (self , 'ip_addresses' ):
355- self .populate ()
371+ self .populate ()
356372
357373 # server can have several public IPs
358374 public_ip_addrs = []
359375 for ip_addr in self .ip_addresses :
360- if ip_addr .access == 'public' :
361- public_ip_addrs .append (ip_addr )
376+ if ip_addr .access == 'public' :
377+ public_ip_addrs .append (ip_addr )
362378
363379 if not public_ip_addrs :
364- return None
380+ return None
365381
366- # prefer IPv4
382+ # prefer addr_family
367383 for ip_addr in public_ip_addrs :
368- if ip_addr .family == 'IPv4' :
369- return ip_addr .address
384+ if ip_addr .family == addr_family :
385+ return ip_addr .address
386+
387+ # strict mode: either find addr_family or don't
388+ if strict :
389+ return None
370390
371- # ...but accept IPv6 too
391+ # not stict mode: any public IP will do if addr_family didn't match
372392 return public_ip_addrs [0 ].address
373393
374394
0 commit comments