From d69d5945a71d152bfdfc6649528ebf698867ffef Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Wed, 10 Apr 2013 06:31:02 +0200 Subject: [PATCH] Add method to parse an IP address from a DCC command. --- .../java/net/pterodactylus/irc/Connection.java | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/main/java/net/pterodactylus/irc/Connection.java b/src/main/java/net/pterodactylus/irc/Connection.java index ade43c9..eacf75e 100644 --- a/src/main/java/net/pterodactylus/irc/Connection.java +++ b/src/main/java/net/pterodactylus/irc/Connection.java @@ -27,7 +27,9 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; +import java.net.InetAddress; import java.net.Socket; +import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -56,6 +58,7 @@ import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.eventbus.EventBus; import com.google.common.io.Closeables; +import com.google.common.primitives.Longs; import com.google.common.util.concurrent.AbstractExecutionThreadService; import com.google.common.util.concurrent.Service; @@ -415,6 +418,32 @@ public class Connection extends AbstractExecutionThreadService implements Servic return Optional.absent(); } + /** + * Parses the given {@code ip} and returns an {@link InetAddress} from it. + * + * @param ip + * The IP to parse + * @return The parsed inet address, or {@link Optional#absent()} if no inet + * address could be parsed + */ + private Optional parseInetAddress(String ip) { + Long ipNumber = Longs.tryParse(ip); + if (ipNumber == null) { + return Optional.absent(); + } + + StringBuilder hostname = new StringBuilder(15); + hostname.append((ipNumber >>> 24) & 0xff).append('.'); + hostname.append((ipNumber >>> 16) & 0xff).append('.'); + hostname.append((ipNumber >>> 8) & 0xff).append('.'); + hostname.append(ipNumber & 0xff); + try { + return Optional.of(InetAddress.getByName(hostname.toString())); + } catch (UnknownHostException uhe1) { + return Optional.absent(); + } + } + /** Handles input and output for the connection. */ private class ConnectionHandler implements Closeable { -- 2.7.4