Merge IPUtil and NetworkConstants into IpAddresses and also make naming of methods consistent

This commit is contained in:
Norman Maurer 2012-11-19 05:52:17 +01:00
parent 213c1e3d23
commit 5d13c7d27b
15 changed files with 213 additions and 232 deletions

View File

@ -17,7 +17,7 @@ package io.netty.handler.codec.socks;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import io.netty.util.IPUtil;
import io.netty.util.IpAddresses;
import java.net.IDN;
@ -46,7 +46,7 @@ public final class SocksCmdRequest extends SocksRequest {
}
switch (addressType) {
case IPv4:
if (!IPUtil.isValidIPV4Address(host)) {
if (!IpAddresses.isValidIpV4Address(host)) {
throw new IllegalArgumentException(host + " is not a valid IPv4 address");
}
break;
@ -56,7 +56,7 @@ public final class SocksCmdRequest extends SocksRequest {
}
break;
case IPv6:
if (!IPUtil.isValidIP6Address(host)) {
if (!IpAddresses.isValidIp6Address(host)) {
throw new IllegalArgumentException(host + " is not a valid IPv6 address");
}
break;
@ -116,7 +116,7 @@ public final class SocksCmdRequest extends SocksRequest {
byteBuf.writeByte(addressType.getByteValue());
switch (addressType) {
case IPv4: {
byteBuf.writeBytes(IPUtil.createByteArrayFromIPAddressString(host));
byteBuf.writeBytes(IpAddresses.createByteArrayFromIpAddressString(host));
byteBuf.writeShort(port);
break;
}
@ -129,7 +129,7 @@ public final class SocksCmdRequest extends SocksRequest {
}
case IPv6: {
byteBuf.writeBytes(IPUtil.createByteArrayFromIPAddressString(host));
byteBuf.writeBytes(IpAddresses.createByteArrayFromIpAddressString(host));
byteBuf.writeShort(port);
break;
}

View File

@ -15,31 +15,183 @@
*/
package io.netty.util;
import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* Utility functions for IPV6 operations.
* A class that holds a number of network-related constants.
*
* see Inet6Util from the Apache Harmony project
*
* see org.apache.harmony.util.Inet6Util
* This class borrowed some of its methods from a modified fork of the
* <a href="http://svn.apache.org/repos/asf/harmony/enhanced/java/branches/java6/classlib/modules/luni/
* src/main/java/org/apache/harmony/luni/util/Inet6Util.java">Inet6Util class</a> which was part of Apache Harmony.
*/
public final class IPUtil {
public final class IpAddresses {
private IPUtil() {
// make this class a an utility class non-instantiable
/**
* The {@link InetAddress} representing the host machine
*
* We cache this because some machines take almost forever to return from
* {@link InetAddress}.getLocalHost(). This may be due to incorrect
* configuration of the hosts and DNS client configuration files.
*/
public static final InetAddress LOCALHOST;
/**
* The loopback {@link NetworkInterface} on the current machine
*/
public static final NetworkInterface LOOPBACK_IF;
/**
* The SOMAXCONN value of the current machine. If failed to get the value, 3072 is used as a
* default value.
*/
public static final int SOMAXCONN;
/**
* The logger being used by this class
*/
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(IpAddresses.class);
static {
//Start the process of discovering localhost
InetAddress localhost;
try {
localhost = InetAddress.getLocalHost();
validateHost(localhost);
} catch (IOException e) {
// The default local host names did not work. Try hard-coded IPv4 address.
try {
localhost = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
validateHost(localhost);
} catch (IOException e1) {
// The hard-coded IPv4 address did not work. Try hard coded IPv6 address.
try {
localhost = InetAddress.getByAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 });
validateHost(localhost);
} catch (IOException e2) {
throw new Error("Failed to resolve localhost - incorrect network configuration?", e2);
}
}
}
LOCALHOST = localhost;
//Prepare to get the local NetworkInterface
NetworkInterface loopbackInterface;
try {
//Automatically get the loopback interface
loopbackInterface = NetworkInterface.getByInetAddress(LOCALHOST);
} catch (SocketException e) {
//No? Alright. There is a backup!
loopbackInterface = null;
}
//Check to see if a network interface was not found
if (loopbackInterface == null) {
try {
//Start iterating over all network interfaces
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
interfaces.hasMoreElements();) {
//Get the "next" interface
NetworkInterface networkInterface = interfaces.nextElement();
//Check to see if the interface is a loopback interface
if (networkInterface.isLoopback()) {
//Phew! The loopback interface was found.
loopbackInterface = networkInterface;
//No need to keep iterating
break;
}
}
} catch (SocketException e) {
//Nope. Can't do anything else, sorry!
logger.error("Failed to enumerate network interfaces", e);
}
}
//Set the loopback interface constant
LOOPBACK_IF = loopbackInterface;
int somaxconn = 3072;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("/proc/sys/net/core/somaxconn"));
somaxconn = Integer.parseInt(in.readLine());
} catch (Exception e) {
// Failed to get SOMAXCONN
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Ignored.
}
}
}
SOMAXCONN = somaxconn;
}
private static void validateHost(InetAddress host) throws IOException {
ServerSocket ss = null;
Socket s1 = null;
Socket s2 = null;
try {
ss = new ServerSocket();
ss.setReuseAddress(false);
ss.bind(new InetSocketAddress(host, 0));
s1 = new Socket(host, ss.getLocalPort());
s2 = ss.accept();
} finally {
if (s2 != null) {
try {
s2.close();
} catch (IOException e) {
// Ignore
}
}
if (s1 != null) {
try {
s1.close();
} catch (IOException e) {
// Ignore
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
// Ignore
}
}
}
}
/**
* Creates an byte[] based on an ipAddressString. No error handling is
* performed here.
*/
public static byte[] createByteArrayFromIPAddressString(
public static byte[] createByteArrayFromIpAddressString(
String ipAddressString) {
if (isValidIPV4Address(ipAddressString)) {
if (isValidIpV4Address(ipAddressString)) {
StringTokenizer tokenizer = new StringTokenizer(ipAddressString,
".");
String token;
@ -155,7 +307,7 @@ public final class IPUtil {
/** Converts a 4 character hex word into a 2 byte word equivalent */
private static void convertToBytes(String hexWord, byte[] ipByteArray,
int byteIndex) {
int byteIndex) {
int hexWordLength = hexWord.length();
int hexWordIndex = 0;
@ -229,7 +381,7 @@ public final class IPUtil {
return 0;
}
public static boolean isValidIP6Address(String ipAddress) {
public static boolean isValidIp6Address(String ipAddress) {
int length = ipAddress.length();
boolean doubleColon = false;
int numberOfColons = 0;
@ -279,7 +431,7 @@ public final class IPUtil {
if (numberOfPeriods > 3) {
return false;
}
if (!isValidIP4Word(word.toString())) {
if (!isValidIp4Word(word.toString())) {
return false;
}
if (numberOfColons != 6 && !doubleColon) {
@ -354,7 +506,7 @@ public final class IPUtil {
// Check if we have an IPv4 ending
if (numberOfPeriods > 0) {
if (numberOfPeriods != 3 || !isValidIP4Word(word.toString())) {
if (numberOfPeriods != 3 || !isValidIp4Word(word.toString())) {
return false;
}
} else {
@ -378,7 +530,7 @@ public final class IPUtil {
return true;
}
public static boolean isValidIP4Word(String word) {
public static boolean isValidIp4Word(String word) {
char c;
if (word.length() < 1 || word.length() > 3) {
return false;
@ -406,7 +558,7 @@ public final class IPUtil {
* @return true, if the string represents an IPV4 address in dotted
* notation, false otherwise
*/
public static boolean isValidIPV4Address(String value) {
public static boolean isValidIpV4Address(String value) {
int periods = 0;
int i;
@ -450,4 +602,10 @@ public final class IPUtil {
return true;
}
/**
* A constructor to stop this class being constructed.
*/
private IpAddresses() {
// Unused
}
}

View File

@ -1,185 +0,0 @@
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util;
import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
/**
* A class that holds a number of network-related constants.
*/
public final class NetworkConstants {
/**
* The {@link InetAddress} representing the host machine
*
* We cache this because some machines take almost forever to return from
* {@link InetAddress}.getLocalHost(). This may be due to incorrect
* configuration of the hosts and DNS client configuration files.
*/
public static final InetAddress LOCALHOST;
/**
* The loopback {@link NetworkInterface} on the current machine
*/
public static final NetworkInterface LOOPBACK_IF;
/**
* The SOMAXCONN value of the current machine. If failed to get the value, 3072 is used as a
* default value.
*/
public static final int SOMAXCONN;
/**
* The logger being used by this class
*/
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(NetworkConstants.class);
static {
//Start the process of discovering localhost
InetAddress localhost;
try {
localhost = InetAddress.getLocalHost();
validateHost(localhost);
} catch (IOException e) {
// The default local host names did not work. Try hard-coded IPv4 address.
try {
localhost = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
validateHost(localhost);
} catch (IOException e1) {
// The hard-coded IPv4 address did not work. Try hard coded IPv6 address.
try {
localhost = InetAddress.getByAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 });
validateHost(localhost);
} catch (IOException e2) {
throw new Error("Failed to resolve localhost - incorrect network configuration?", e2);
}
}
}
LOCALHOST = localhost;
//Prepare to get the local NetworkInterface
NetworkInterface loopbackInterface;
try {
//Automatically get the loopback interface
loopbackInterface = NetworkInterface.getByInetAddress(LOCALHOST);
} catch (SocketException e) {
//No? Alright. There is a backup!
loopbackInterface = null;
}
//Check to see if a network interface was not found
if (loopbackInterface == null) {
try {
//Start iterating over all network interfaces
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
interfaces.hasMoreElements();) {
//Get the "next" interface
NetworkInterface networkInterface = interfaces.nextElement();
//Check to see if the interface is a loopback interface
if (networkInterface.isLoopback()) {
//Phew! The loopback interface was found.
loopbackInterface = networkInterface;
//No need to keep iterating
break;
}
}
} catch (SocketException e) {
//Nope. Can't do anything else, sorry!
logger.error("Failed to enumerate network interfaces", e);
}
}
//Set the loopback interface constant
LOOPBACK_IF = loopbackInterface;
int somaxconn = 3072;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("/proc/sys/net/core/somaxconn"));
somaxconn = Integer.parseInt(in.readLine());
} catch (Exception e) {
// Failed to get SOMAXCONN
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Ignored.
}
}
}
SOMAXCONN = somaxconn;
}
private static void validateHost(InetAddress host) throws IOException {
ServerSocket ss = null;
Socket s1 = null;
Socket s2 = null;
try {
ss = new ServerSocket();
ss.setReuseAddress(false);
ss.bind(new InetSocketAddress(host, 0));
s1 = new Socket(host, ss.getLocalPort());
s2 = ss.accept();
} finally {
if (s2 != null) {
try {
s2.close();
} catch (IOException e) {
// Ignore
}
}
if (s1 != null) {
try {
s1.close();
} catch (IOException e) {
// Ignore
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
// Ignore
}
}
}
}
/**
* A constructor to stop this class being constructed.
*/
private NetworkConstants() {
// Unused
}
}

View File

@ -19,16 +19,16 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class NetworkConstantsTest {
public class IpAddressesTest {
@Test
public void testLocalhost() {
assertNotNull(NetworkConstants.LOCALHOST);
assertNotNull(IpAddresses.LOCALHOST);
}
@Test
public void testLoopback() {
assertNotNull(NetworkConstants.LOOPBACK_IF);
assertNotNull(IpAddresses.LOOPBACK_IF);
}
}

View File

@ -20,7 +20,7 @@ import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import io.netty.testsuite.transport.socket.SocketTestPermutation.Factory;
import io.netty.testsuite.util.TestUtils;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -47,7 +47,7 @@ public abstract class AbstractClientSocketTest {
for (Factory<Bootstrap> e: COMBO) {
cb = e.newInstance();
addr = new InetSocketAddress(
NetworkConstants.LOCALHOST, TestUtils.getFreePort());
IpAddresses.LOCALHOST, TestUtils.getFreePort());
cb.remoteAddress(addr);
logger.info(String.format(

View File

@ -21,7 +21,8 @@ import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import io.netty.testsuite.transport.socket.SocketTestPermutation.Factory;
import io.netty.testsuite.util.TestUtils;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import org.junit.Rule;
import org.junit.rules.TestName;
@ -51,7 +52,7 @@ public abstract class AbstractDatagramTest {
sb = e.getKey().newInstance();
cb = e.getValue().newInstance();
addr = new InetSocketAddress(
NetworkConstants.LOCALHOST, TestUtils.getFreePort());
IpAddresses.LOCALHOST, TestUtils.getFreePort());
sb.localAddress(addr);
cb.localAddress(0).remoteAddress(addr);

View File

@ -21,7 +21,7 @@ import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import io.netty.testsuite.transport.socket.SocketTestPermutation.Factory;
import io.netty.testsuite.util.TestUtils;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import org.junit.Rule;
import org.junit.rules.TestName;
@ -53,7 +53,7 @@ public abstract class AbstractSctpTest {
sb = e.getKey().newInstance();
cb = e.getValue().newInstance();
addr = new InetSocketAddress(
NetworkConstants.LOCALHOST, TestUtils.getFreePort());
IpAddresses.LOCALHOST, TestUtils.getFreePort());
sb.localAddress(addr);
cb.remoteAddress(addr);

View File

@ -20,7 +20,8 @@ import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import io.netty.testsuite.transport.socket.SocketTestPermutation.Factory;
import io.netty.testsuite.util.TestUtils;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import org.junit.Rule;
import org.junit.rules.TestName;
@ -46,7 +47,7 @@ public abstract class AbstractServerSocketTest {
for (Factory<ServerBootstrap> e: COMBO) {
sb = e.newInstance();
addr = new InetSocketAddress(
NetworkConstants.LOCALHOST, TestUtils.getFreePort());
IpAddresses.LOCALHOST, TestUtils.getFreePort());
sb.localAddress(addr);
logger.info(String.format(

View File

@ -21,7 +21,8 @@ import io.netty.logging.InternalLogger;
import io.netty.logging.InternalLoggerFactory;
import io.netty.testsuite.transport.socket.SocketTestPermutation.Factory;
import io.netty.testsuite.util.TestUtils;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import org.junit.Rule;
import org.junit.rules.TestName;
@ -53,7 +54,7 @@ public abstract class AbstractSocketTest {
sb = e.getKey().newInstance();
cb = e.getValue().newInstance();
addr = new InetSocketAddress(
NetworkConstants.LOCALHOST, TestUtils.getFreePort());
IpAddresses.LOCALHOST, TestUtils.getFreePort());
sb.localAddress(addr);
cb.remoteAddress(addr);

View File

@ -24,7 +24,7 @@ import io.netty.channel.ChannelOption;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.oio.OioDatagramChannel;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import org.junit.Ignore;
import org.junit.Test;
@ -56,9 +56,9 @@ public class DatagramMulticastTest extends AbstractDatagramTest {
cb.handler(mhandler);
sb.option(ChannelOption.IP_MULTICAST_IF, NetworkConstants.LOOPBACK_IF);
sb.option(ChannelOption.IP_MULTICAST_IF, IpAddresses.LOOPBACK_IF);
sb.option(ChannelOption.SO_REUSEADDR, true);
cb.option(ChannelOption.IP_MULTICAST_IF, NetworkConstants.LOOPBACK_IF);
cb.option(ChannelOption.IP_MULTICAST_IF, IpAddresses.LOOPBACK_IF);
cb.option(ChannelOption.SO_REUSEADDR, true);
cb.localAddress(addr.getPort());
@ -75,13 +75,13 @@ public class DatagramMulticastTest extends AbstractDatagramTest {
String group = "230.0.0.1";
InetSocketAddress groupAddress = new InetSocketAddress(group, addr.getPort());
cc.joinGroup(groupAddress, NetworkConstants.LOOPBACK_IF).sync();
cc.joinGroup(groupAddress, IpAddresses.LOOPBACK_IF).sync();
sc.write(new DatagramPacket(Unpooled.copyInt(1), groupAddress)).sync();
assertTrue(mhandler.await());
// leave the group
cc.leaveGroup(groupAddress, NetworkConstants.LOOPBACK_IF).sync();
cc.leaveGroup(groupAddress, IpAddresses.LOOPBACK_IF).sync();
// sleep a second to make sure we left the group
Thread.sleep(1000);

View File

@ -29,7 +29,7 @@ import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.spdy.SpdyConstants;
import io.netty.handler.codec.spdy.SpdyFrameDecoder;
import io.netty.handler.codec.spdy.SpdyFrameEncoder;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import java.io.IOException;
import java.net.InetSocketAddress;
@ -197,7 +197,7 @@ public class SocketSpdyEchoTest extends AbstractSocketTest {
Channel sc = sb.localAddress(0).bind().sync().channel();
int port = ((InetSocketAddress) sc.localAddress()).getPort();
Channel cc = cb.remoteAddress(NetworkConstants.LOCALHOST, port).connect().sync().channel();
Channel cc = cb.remoteAddress(IpAddresses.LOCALHOST, port).connect().sync().channel();
cc.write(frames);
while (ch.counter < frames.writerIndex() - ignoredBytes) {

View File

@ -15,7 +15,7 @@
*/
package io.netty.testsuite.util;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import java.io.IOException;
import java.net.InetSocketAddress;
@ -64,7 +64,7 @@ public final class TestUtils {
ss = new ServerSocket();
ss.setReuseAddress(false);
ss.bind(new InetSocketAddress(NetworkConstants.LOCALHOST, port));
ss.bind(new InetSocketAddress(IpAddresses.LOCALHOST, port));
ss.close();
return port;

View File

@ -21,7 +21,7 @@ import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultChannelConfig;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import java.io.IOException;
import java.util.Map;
@ -36,7 +36,7 @@ import static com.sun.nio.sctp.SctpStandardSocketOptions.SO_SNDBUF;
public class DefaultSctpServerChannelConfig extends DefaultChannelConfig implements SctpServerChannelConfig {
private final SctpServerChannel serverChannel;
private volatile int backlog = NetworkConstants.SOMAXCONN;
private volatile int backlog = IpAddresses.SOMAXCONN;
/**
* Creates a new instance.

View File

@ -21,7 +21,7 @@ import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultChannelConfig;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import java.net.ServerSocket;
import java.net.SocketException;
@ -34,7 +34,7 @@ public class DefaultServerSocketChannelConfig extends DefaultChannelConfig
implements ServerSocketChannelConfig {
private final ServerSocket socket;
private volatile int backlog = NetworkConstants.SOMAXCONN;
private volatile int backlog = IpAddresses.SOMAXCONN;
/**
* Creates a new instance.

View File

@ -22,7 +22,7 @@ import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultChannelConfig;
import io.netty.channel.socket.ServerSocketChannelConfig;
import io.netty.util.NetworkConstants;
import io.netty.util.IpAddresses;
import java.io.IOException;
import java.net.SocketOption;
@ -38,6 +38,7 @@ import java.util.concurrent.atomic.AtomicReference;
final class AioServerSocketChannelConfig extends DefaultChannelConfig
implements ServerSocketChannelConfig {
<<<<<<< HEAD
private final AtomicReference<AsynchronousServerSocketChannel> channel
= new AtomicReference<AsynchronousServerSocketChannel>();
private volatile int backlog = NetworkConstants.SOMAXCONN;
@ -53,6 +54,10 @@ final class AioServerSocketChannelConfig extends DefaultChannelConfig
*/
AioServerSocketChannelConfig() {
}
=======
private final AsynchronousServerSocketChannel channel;
private volatile int backlog = IpAddresses.SOMAXCONN;
>>>>>>> 9e370a3... Merge IPUtil and NetworkConstants into IpAddresses and also make naming of methods consistent
/**
* Creates a new instance with the given {@link AsynchronousServerSocketChannel} assigned to it.