Rewrite host parsing to account for IPv6.

This commit is contained in:
md_5 2016-01-14 09:52:16 +11:00
parent a1895c556f
commit 1182affa09
2 changed files with 72 additions and 6 deletions

View File

@ -2,6 +2,8 @@ package net.md_5.bungee;
import com.google.common.base.Joiner;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;
/**
@ -10,7 +12,7 @@ import java.util.UUID;
public class Util
{
private static final int DEFAULT_PORT = 25565;
public static final int DEFAULT_PORT = 25565;
/**
* Method to transform human readable addresses into usable address objects.
@ -20,13 +22,16 @@ public class Util
*/
public static InetSocketAddress getAddr(String hostline)
{
String[] split = hostline.split( ":" );
int port = DEFAULT_PORT;
if ( split.length > 1 )
URI uri;
try
{
port = Integer.parseInt( split[1] );
uri = new URI( "tcp://" + hostline );
} catch ( URISyntaxException ex )
{
throw new IllegalArgumentException( "Bad hostline", ex );
}
return new InetSocketAddress( split[0], port );
return new InetSocketAddress( uri.getHost(), ( uri.getPort() ) == -1 ? DEFAULT_PORT : uri.getPort() );
}
/**

View File

@ -0,0 +1,61 @@
package net.md_5.bungee.util;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collection;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.Util;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RequiredArgsConstructor
@RunWith(Parameterized.class)
public class AddressParseTest
{
@Parameters
public static Collection<Object[]> data()
{
return Arrays.asList( new Object[][]
{
{
"127.0.0.1", "127.0.0.1", Util.DEFAULT_PORT
},
{
"127.0.0.1:1337", "127.0.0.1", 1337
},
{
"[::1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT
},
{
"[0:0:0:0::1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT
},
{
"[0:0:0:0:0:0:0:1]", "0:0:0:0:0:0:0:1", Util.DEFAULT_PORT
},
{
"[::1]:1337", "0:0:0:0:0:0:0:1", 1337
},
{
"[0:0:0:0::1]:1337", "0:0:0:0:0:0:0:1", 1337
},
{
"[0:0:0:0:0:0:0:1]:1337", "0:0:0:0:0:0:0:1", 1337
}
} );
}
private final String line;
private final String host;
private final int port;
@Test
public void test()
{
InetSocketAddress parsed = Util.getAddr( line );
Assert.assertEquals( host, parsed.getHostString() );
Assert.assertEquals( port, parsed.getPort() );
}
}