package com.forerunnergames.tools.net;

import com.forerunnergames.tools.common.Arguments;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultExternalAddressResolver implements ExternalAddressResolver
{
  protected final Logger log = LoggerFactory.getLogger (getClass ());
  private final String url;

  /**
   * @param url
   *          The URL where the ip address will be printed in plain text on the first line of the web page.
   */
  public DefaultExternalAddressResolver (final String url)
  {
    Arguments.checkIsNotNull (url, "url");

    this.url = url;
  }

  @Override
  public String resolveIp ()
  {
    BufferedReader reader = null;

    try
    {
      reader = new BufferedReader (new InputStreamReader (new URL (url).openStream ()));

      return reader.readLine ();
    }
    catch (final IOException e)
    {
      log.error ("Could not resolve external ip address using URL [{}]\n\nCause:\n\n{}", url, e);

      return "";
    }
    finally
    {
      if (reader != null)
      {
        try
        {
          reader.close ();
        }
        catch (final IOException ignored)
        {
        }
      }
    }
  }
}

@@ -83,16 +83,113 @@
 guments;
+%0Aimport com.forerunnergames.tools.common.Exceptions;%0A%0Aimport com.google.common.net.InetAddresses;
 %0A%0Aimport
@@ -997,33 +997,234 @@
     
-return reader.readLine ()
+final String ipAddress = reader.readLine ();%0A%0A      if (ipAddress == null %7C%7C !InetAddresses.isInetAddress (ipAddress))%0A      %7B%0A        Exceptions.throwIO (%22Invalid IP address %5B%7B%7D%5D.%22, ipAddress);%0A      %7D%0A%0A      return ipAddress
 ;%0A  

Make DefaultExternalAddressResolver more robust.