Methods Summary |
---|
public static java.lang.String | getCanonicalHostName()This method returns the fully qualified name of the host. If
the name can't be resolved (on windows if there isn't a domain specified), just
host name is returned
String hostname=null;
String defaultHostname=InetAddress.getLocalHost().getHostName();
// look for full name
hostname=InetAddress.getLocalHost().getCanonicalHostName();
// check to see if ip returned or canonical hostname is different than hostname
// It is possible for dhcp connected computers to have an erroneous name returned
// that is created by the dhcp server. If that happens, return just the default hostname
if (hostname.equals(InetAddress.getLocalHost().getHostAddress()) ||
!hostname.startsWith(defaultHostname)) {
// don't want IP or canonical hostname, this will cause a lot of problems for dhcp users
// get just plan host name instead
hostname=defaultHostname;
}
return hostname;
|
public static int | getFreePort(java.lang.String hostName, int startingPort, int endingPort)Returns a random port in the specified range
int range = endingPort - startingPort;
int port = 0;
if (range > 0) {
Random r = new Random();
while (true) {
port = r.nextInt(range + 1) + startingPort;
if (isPortFree(hostName, port)) {
break;
}
}
}
return port;
|
public static int | getFreePort()Gets a free port at the time of call to this method.
The logic leverages the built in java.net.ServerSocket implementation
which binds a server socket to a free port when instantiated with
a port 0 .
Note that this method guarantees the availability of the port
only at the time of call. The method does not bind to this port.
Checking for free port can fail for several reasons which may
indicate potential problems with the system. This method acknowledges
the fact and following is the general contract:
Best effort is made to find a port which can be bound to. All
the exceptional conditions in the due course are considered SEVERE.
If any exceptional condition is experienced, 0
is returned, indicating that the method failed for some reasons and
the callers should take the corrective action. (The method need not
always throw an exception for this).
Method is synchronized on this class.
int freePort = 0;
boolean portFound = false;
ServerSocket serverSocket = null;
synchronized (NetUtils.class)
{
try
{
/*following call normally returns the free port,
to which the ServerSocket is bound. */
serverSocket = new ServerSocket(0);
freePort = serverSocket.getLocalPort();
portFound = true;
}
catch(Exception e)
{
//squelch the exception
}
finally
{
if (!portFound)
{
freePort = 0;
}
try
{
if (serverSocket != null)
{
serverSocket.close();
if (! serverSocket.isClosed())
{
throw new Exception("local exception ...");
}
}
}
catch(Exception e)
{
//squelch the exception
freePort = 0;
}
}
return freePort;
}
|
public static java.net.InetAddress[] | getHostAddresses()
try
{
String hname = getHostName();
if(hname == null)
return null;
return InetAddress.getAllByName(hname);
}
catch(Exception e)
{
return null;
}
|
public static java.lang.String[] | getHostIPs()
try
{
InetAddress[] adds = getHostAddresses();
if(adds == null)
return null;
String[] ips = new String[adds.length];
for(int i = 0; i < adds.length; i++)
{
String ip = trimIP(adds[i].toString());
ips[i] = ip;
}
return ips;
}
catch(Exception e)
{
return null;
}
|
public static java.lang.String | getHostName()
///////////////////////////////////////////////////////////////////////////
try
{
return InetAddress.getLocalHost().getHostName();
}
catch(Exception e)
{
return null;
}
|
public static int | getNextFreePort(java.lang.String hostName, int port)Get the next free port (incrementing by 1)
while (port++ < MAX_PORT) {
if (isPortFree(hostName, port)) {
return port;
}
}
return 0;
|
public static byte[] | ip2bytes(java.lang.String ip)
try
{
// possibilities: "1.1.1.1", "frodo/1.1.1.1", "frodo.foo.com/1.1.1.1"
ip = trimIP(ip);
StringTokenizer stk = new StringTokenizer(ip, ".");
byte[] bytes = new byte[stk.countTokens()];
for(int i = 0; stk.hasMoreTokens(); i++)
{
String num = stk.nextToken();
int inum = Integer.parseInt(num);
bytes[i] = (byte)inum;
//System.out.println("token: " + inum);
}
return bytes;
}
catch(NumberFormatException nfe)
{
return null;
}
|
public static boolean | isLocal(java.lang.String ip)
if(ip == null)
return false;
ip = trimIP(ip);
if(isLocalHost(ip))
return true;
String[] myIPs = getHostIPs();
if(myIPs == null)
return false;
for(int i = 0; i < myIPs.length; i++)
{
if(ip.equals(myIPs[i]))
return true;
}
return false;
|
public static boolean | isLocalHost(java.lang.String ip)
if(ip == null)
return false;
ip = trimIP(ip);
return ip.equals(LOCALHOST_IP);
|
public static boolean | isPortFree(java.lang.String hostName, int portNumber)
if(portNumber <= 0 || portNumber > MAX_PORT)
return false;
if(hostName == null || isThisMe(hostName))
return isPortFreeServer(portNumber);
else
return isPortFreeClient(hostName, portNumber);
|
public static boolean | isPortFree(int portNumber)
return isPortFree(null, portNumber);
|
private static boolean | isPortFreeClient(java.lang.String hostName, int portNumber)
try
{
// WBN - I have no idea why I'm messing with these streams!
// I lifted the code from installer. Apparently if you just
// open a socket on a free port and catch the exception something
// will go wrong in Windows.
// Feel free to change it if you know EXACTLY what you'return doing
//If the host name is null, assume localhost
if (hostName == null) {
hostName = getHostName();
}
Socket socket = new Socket(hostName, portNumber);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
os.close();
os = null;
is.close();
is = null;
socket.close();
socket = null;
}
catch (Exception e)
{
// Nobody is listening on this port
return true;
}
return false;
|
private static boolean | isPortFreeServer(int port)
try
{
ServerSocket ss = new ServerSocket(port);
ss.close();
return true;
}
catch (Exception e)
{
return false;
}
|
public static boolean | isPortStringValid(java.lang.String portNumber)
try {
return isPortValid(Integer.parseInt(portNumber));
} catch (NumberFormatException ex) {
return false;
}
|
public static boolean | isPortValid(int portNumber)
if (portNumber >=0 && portNumber <= MAX_PORT) {
return true;
} else {
return false;
}
|
public static boolean | isRemote(java.lang.String ip)
return !isLocal(ip);
|
public static boolean | isSecurePort(java.lang.String hostname, int port)This method accepts a hostname and port #. It uses this information
to attempt to connect to the port, send a test query, analyze the
result to determine if the port is secure or unsecure (currently only
http / https is supported).
// Open the socket w/ a 4 second timeout
Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostname, port), 4000);
// Send an https query (w/ trailing http query)
java.io.OutputStream ostream = socket.getOutputStream();
ostream.write(TEST_QUERY);
// Get the result
java.io.InputStream istream = socket.getInputStream();
int count=0;
while (count<20) {
// Wait up to 4 seconds
try {
if (istream.available() > 0) {
break;
}
Thread.sleep(200);
} catch (InterruptedException ex) {
}
count++;
}
byte[] input = new byte[istream.available()];
int len = istream.read(input);
// Close the socket
socket.close();
// Determine protocol from result
// Can't read https response w/ OpenSSL (or equiv), so use as
// default & try to detect an http response.
String response = new String(input).toLowerCase();
boolean isSecure = true;
if (response.length() == 0) {
isSecure = false;
} else if (response.startsWith("http/1.")) {
isSecure = false;
} else if (response.indexOf("<html") != -1) {
isSecure = false;
} else if (response.indexOf("connection: ") != -1) {
isSecure = false;
}
return isSecure;
|
private static boolean | isThisMe(java.lang.String hostname)
///////////////////////////////////////////////////////////////////////////
try
{
InetAddress[] myadds = getHostAddresses();
InetAddress[] theiradds = InetAddress.getAllByName(hostname);
for(int i = 0; i < theiradds.length; i++)
{
if(theiradds[i].isLoopbackAddress())
return true;
for(int j = 0; j < myadds.length; j++)
{
if(myadds[j].equals(theiradds[i]))
return true;
}
}
}
catch(Exception e)
{
}
return false;
|
public static void | main(java.lang.String[] args)
System.out.println("80: " + isPortFree(80));
System.out.println("777: " + isPortFree(777));
System.out.println("8000: " + isPortFree(8000));
|
public static java.lang.String | trimIP(java.lang.String ip)
if(ip == null || ip.length() <= 0)
return ip;
int index = ip.lastIndexOf('/");
if(index >= 0)
return ip.substring(++index);
return ip;
|