Java/Network Protocol/IP Address

Материал из Java эксперт
Перейти к: навигация, поиск

A class that performs some subnet calculations given a network address and a subnet mask.

   <source lang="java">
 

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.
*/

import java.util.regex.Matcher; import java.util.regex.Pattern; /**

* A class that performs some subnet calculations given a network address and a subnet mask. 
* @see http://www.faqs.org/rfcs/rfc1519.html
* @author <rwinston@apache.org>
* @since 2.0
*/

public class SubnetUtils {

   private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})";
   private static final String SLASH_FORMAT = IP_ADDRESS + "/(\\d{1,3})";
   private static final Pattern addressPattern = Pattern.rupile(IP_ADDRESS);
   private static final Pattern cidrPattern = Pattern.rupile(SLASH_FORMAT);
   private static final int NBITS = 32;
   private int netmask = 0;
   private int address = 0;
   private int network = 0;
   private int broadcast = 0;
   /**
    * Constructor that takes a CIDR-notation string, e.g. "192.168.0.1/16"
    * @param cidrNotation A CIDR-notation string, e.g. "192.168.0.1/16"
    */
   public SubnetUtils(String cidrNotation) {
       calculate(cidrNotation);
   }
   /**
    * Constructor that takes two dotted decimal addresses. 
    * @param address An IP address, e.g. "192.168.0.1"
    * @param mask A dotted decimal netmask e.g. "255.255.0.0"
    */
   public SubnetUtils(String address, String mask) {
       calculate(toCidrNotation(address, mask));
   }
   /**
    * Convenience container for subnet summary information.
    *
    */
   public final class SubnetInfo {
       private SubnetInfo() {}
       private int netmask()       { return netmask; }
       private int network()       { return network; }
       private int address()       { return address; }
       private int broadcast()     { return broadcast; }
       private int low()           { return network() + 1; }
       private int high()          { return broadcast() - 1; }
       public boolean isInRange(String address)    { return isInRange(toInteger(address)); }
       private boolean isInRange(int address)      { return ((address-low()) <= (high()-low())); }
       public String getBroadcastAddress()         { return format(toArray(broadcast())); }
       public String getNetworkAddress()           { return format(toArray(network())); }
       public String getNetmask()                  { return format(toArray(netmask())); }
       public String getAddress()                  { return format(toArray(address())); }
       public String getLowAddress()               { return format(toArray(low())); }
       public String getHighAddress()              { return format(toArray(high())); }
       public int getAddressCount()                { return (broadcast() - low()); }
       public int asInteger(String address)        { return toInteger(address); }
       
       public String getCidrSignature() { 
           return toCidrNotation(
                   format(toArray(address())), 
                   format(toArray(netmask()))
           );
       }
       
       public String[] getAllAddresses() { 
           String[] addresses = new String[getAddressCount()];
           for (int add = low(), j=0; add <= high(); ++add, ++j) {
               addresses[j] = format(toArray(add));
           }
           return addresses;
       }
   }
   /**
    * Return a {@link SubnetInfo} instance that contains subnet-specific statistics
    * @return
    */
   public final SubnetInfo getInfo() { return new SubnetInfo(); }
   /*
    * Initialize the internal fields from the supplied CIDR mask
    */
   private void calculate(String mask) {
       Matcher matcher = cidrPattern.matcher(mask);
       if (matcher.matches()) {
           address = matchAddress(matcher);
           /* Create a binary netmask from the number of bits specification /x */
           int cidrPart = rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS-1);
           for (int j = 0; j < cidrPart; ++j) {
               netmask |= (1 << 31-j);
           }
           /* Calculate base network address */
           network = (address & netmask);
           /* Calculate broadcast address */
           broadcast = network | ~(netmask);
       }
       else 
           throw new IllegalArgumentException("Could not parse [" + mask + "]");
   }
   /*
    * Convert a dotted decimal format address to a packed integer format
    */
   private int toInteger(String address) {
       Matcher matcher = addressPattern.matcher(address);
       if (matcher.matches()) {
           return matchAddress(matcher);
       }
       else
           throw new IllegalArgumentException("Could not parse [" + address + "]");
   }
   /*
    * Convenience method to extract the components of a dotted decimal address and 
    * pack into an integer using a regex match
    */
   private int matchAddress(Matcher matcher) {
       int addr = 0;
       for (int i = 1; i <= 4; ++i) { 
           int n = (rangeCheck(Integer.parseInt(matcher.group(i)), 0, 255));
           addr |= ((n & 0xff) << 8*(4-i));
       }
       return addr;
   }
   /*
    * Convert a packed integer address into a 4-element array
    */
   private int[] toArray(int val) {
       int ret[] = new int[4];
       for (int j = 3; j >= 0; --j)
           ret[j] |= ((val >>> 8*(3-j)) & (0xff));
       return ret;
   }
   /*
    * Convert a 4-element array into dotted decimal format
    */
   private String format(int[] octets) {
       StringBuilder str = new StringBuilder();
       for (int i =0; i < octets.length; ++i){
           str.append(octets[i]);
           if (i != octets.length - 1) {
               str.append("."); 
           }
       }
       return str.toString();
   }
   /*
    * Convenience function to check integer boundaries
    */
   private int rangeCheck(int value, int begin, int end) {
       if (value >= begin && value <= end)
           return value;
       throw new IllegalArgumentException("Value out of range: [" + value + "]");
   }
   /*
    * Count the number of 1-bits in a 32-bit integer using a divide-and-conquer strategy
    * see Hacker"s Delight section 5.1 
    */
   int pop(int x) {
       x = x - ((x >>> 1) & 0x55555555); 
       x = (x & 0x33333333) + ((x >>> 2) & 0x33333333); 
       x = (x + (x >>> 4)) & 0x0F0F0F0F; 
       x = x + (x >>> 8); 
       x = x + (x >>> 16); 
       return x & 0x0000003F; 
   } 
   /* Convert two dotted decimal addresses to a single xxx.xxx.xxx.xxx/yy format
    * by counting the 1-bit population in the mask address. (It may be better to count 
    * NBITS-#trailing zeroes for this case)
    */
   private String toCidrNotation(String addr, String mask) {
       return addr + "/" + pop(toInteger(mask));
   }

}


 </source>
   
  
 
  



An nslookup clone in Java

   <source lang="java">
  

import java.io.DataInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; /**

* An "nslookup" clone in Java.
* 
* @author Elliot Rusty Harold, O"Reilly & Associates
*/

public class JavaLookup {

 public static void main(String args[]) {
   if (args.length > 0) { // use command line
     for (int i = 0; i < args.length; i++) {
       lookup(args[i]);
     }
   } else {
     DataInputStream myInputStream = new DataInputStream(System.in);
     System.out
         .println("Enter names and IP addresses. Enter \"exit\" to quit.");
     while (true) {
       String s;
       try {
         s = myInputStream.readLine();
       } catch (IOException e) {
         break;
       }
       if (s.equals("exit"))
         break;
       if (s.equals("quit"))
         break;
       if (s.charAt(0) == "\004")
         break; // unix ^D
       lookup(s);
     }
   }
 } /* end main */
 private static void lookup(String s) {
   InetAddress thisComputer;
   byte[] address;
   // get the bytes of the IP address
   try {
     thisComputer = InetAddress.getByName(s);
     address = thisComputer.getAddress();
   } catch (UnknownHostException ue) {
     System.out.println("Cannot find host " + s);
     return;
   }
   if (isHostname(s)) {
     // Print the IP address
     for (int i = 0; i < address.length; i++) {
       int unsignedByte = address[i] < 0 ? address[i] + 256
           : address[i];
       System.out.print(unsignedByte + ".");
     }
     System.out.println();
   } else { // this is an IP address
     try {
       System.out.println(InetAddress.getByName(s));
     } catch (UnknownHostException e) {
       System.out.println("Could not lookup the address " + s);
     }
   }
 } // end lookup
 private static boolean isHostname(String s) {
   char[] ca = s.toCharArray();
   // if we see a character that is neither a digit nor a period
   // then s is probably a hostname
   for (int i = 0; i < ca.length; i++) {
     if (!Character.isDigit(ca[i])) {
       if (ca[i] != ".") {
         return true;
       }
     }
   }
   // Everything was either a digit or a period
   // so s looks like an IP address in dotted quad format
   return false;
 } // end isHostName

} // end javalookup



 </source>
   
  
 
  



Convert a hostname to the equivalent IP address

   <source lang="java">
  

import java.net.InetAddress; import java.net.UnknownHostException; public class GetIP {

 public static void main(String[] args) {
   InetAddress address = null;
   try {
     address = InetAddress.getByName("www.jexp.ru");
   } catch (UnknownHostException e) {
     System.exit(2);
   }
   System.out.println(address.getHostName() + "="
       + address.getHostAddress());
   System.exit(0);
 }

}



 </source>
   
  
 
  



Determine the IP address and hostname of the local machine

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] argv) throws Exception {
   InetAddress addr = InetAddress.getLocalHost();
   // Get IP Address
   byte[] ipAddr = addr.getAddress();
   // Get hostname
   String hostname = addr.getHostName();
 }

}


 </source>
   
  
 
  



Display multiple IP addresses

   <source lang="java">
    

import java.net.*; public class GetAllIP {

 public static void main(String [] args) throws Exception {
   InetAddress[] addr = InetAddress.getAllByName("www.jexp.ru");
   for (int i=0;i<addr.length;i++)
     System.out.println(addr[i]);
   }
 }
          
        
   
   
 </source>
   
  
 
  



Get all IP addresses

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] args) throws Exception {
   InetAddress[] addr = InetAddress.getAllByName(args[0]);
   for (int i = 0; i < addr.length; i++)
     System.out.println(addr[i]);
 }

}


 </source>
   
  
 
  



Get canonical host name

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] ipAddr = new byte[] { 127, 0, 0, 1 };
   InetAddress addr = InetAddress.getByAddress(ipAddr);
   String hostnameCanonical = addr.getCanonicalHostName();
 }

}


 </source>
   
  
 
  



Get hostname by a byte array containing the IP address

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] argv) throws Exception {
   byte[] ipAddr = new byte[] { 127, 0, 0, 1 };
   InetAddress addr = InetAddress.getByAddress(ipAddr);
 }

}


 </source>
   
  
 
  



Get IP

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] args) throws Exception {
   InetAddress address = null;
   if (args.length == 0) {
     System.out.println("usage: GetIP host");
     System.exit(1);
   }
   address = InetAddress.getByName(args[0]);
   System.out.println(address.getHostName() + "=" + address.getHostAddress());
   System.exit(0);
 }

}


 </source>
   
  
 
  



Getting the Hostname of an IP Address

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] argv) throws Exception {
   // Get hostname by textual representation of IP address
   InetAddress addr = InetAddress.getByName("127.0.0.1");
 }

}


 </source>
   
  
 
  



Getting the IP Address and Hostname of the Local Machine

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] argv) throws Exception {
   InetAddress addr = InetAddress.getLocalHost();
   // Get IP Address
   byte[] ipAddr = addr.getAddress();
   // Get hostname
   String hostname = addr.getHostName();
 }

}


 </source>
   
  
 
  



Looking for Port: 1024 -- 65536

   <source lang="java">
  

import java.net.*; import java.io.*; public class lookForPorts2 {

 public static void main(String[] args) {
   Socket theSocket;
   String host = "localhost";
   if (args.length > 0) {
     host = args[0];
   }
   try {
     InetAddress theAddress = InetAddress.getByName(host);
     for (int i = 1024; i < 65536; i++) {
       try {
         System.out.println("Looking for port "+ i);
         theSocket = new Socket(theAddress, i);
         System.out.println("There is a server on port " + i + " of " + host);
       } catch (IOException e) {
         // must not be a server on this port
       }
     }
   } catch (UnknownHostException e) {
     System.err.println(e);
   }
 }

}



 </source>
   
  
 
  



Looking for Ports: 0 -- 1024

   <source lang="java">
  

import java.net.*; import java.io.*;

public class lookForPorts {

 public static void main(String[] args) {
   
   Socket theSocket;
   String host = "localhost";
   if (args.length > 0) {
     host = args[0];
   }
   for (int i = 0; i < 1024; i++) {
     try {
       System.out.println("Looking for "+ i);
       theSocket = new Socket(host, i);
       System.out.println("There is a server on port " + i + " of " + host);
     }
     catch (UnknownHostException e) {
       System.err.println(e);
       break;
     }
     catch (IOException e) {
       // must not be a server on this port
     }
   }
 }

}



 </source>
   
  
 
  



Looking for Port: start from 65535

   <source lang="java">
  

import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class lookForPorts3 {

 public static void main(String[] args) {
   Socket theSocket;
   String host = "localhost";
   if (args.length > 0) {
     host = args[0];
   }
   try {
     InetAddress theAddress = InetAddress.getByName(host);
     for (int i = 1; i <= 65535; i++) {
       try {
         theSocket = new Socket(host, i);
         System.out.println("There is a server on port " + i + " of " + host);
         theSocket.close();
       } catch (IOException e) {
         // must not be a server on this port
       }
     }
   } catch (UnknownHostException e) {
     System.err.println(e);
   }
 }

}



 </source>
   
  
 
  



Looking Up the Address of a Host

   <source lang="java">
  

import java.net.InetAddress; import java.net.UnknownHostException; public class DNSLookup {

 public static void main(String args[]) {
   try {
     InetAddress host;
     if (args.length == 0) {
       host = InetAddress.getLocalHost();
     } else {
       host = InetAddress.getByName(args[0]);
     }
     System.out.println("Host:"" + host.getHostName()
         + "" has address: " + host.getHostAddress());
     byte bytes[] = host.getAddress();
     int fourBytes[] = new int[bytes.length];
     for (int i = 0, n = bytes.length; i < n; i++) {
       fourBytes[i] = bytes[i] & 255;
     }
     System.out.println("\t" + fourBytes[0] + "." + fourBytes[1] + "."
         + fourBytes[2] + "." + fourBytes[3]);
   } catch (UnknownHostException e) {
     e.printStackTrace();
   }
 }

}



 </source>
   
  
 
  



Perform Network Lookup with the InetAddress class

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] args) throws Exception{
   InetAddress inetHost = InetAddress.getByName("www.google.ru");
   String hostName = inetHost.getHostName();
   System.out.println(hostName);
   System.out.println(inetHost.getHostAddress());
 }

}


 </source>
   
  
 
  



Report By Address

   <source lang="java">
  

import java.net.InetAddress; import java.net.NetworkInterface; public class Main {

 static public void main(String args[]) throws Exception {
   InetAddress ia = InetAddress.getByName(args[0]);
   NetworkInterface ni = NetworkInterface.getByInetAddress(ia);
   System.out.println(ni);
 }

}


 </source>
   
  
 
  



Resolves hostname and returns ip address as a string

   <source lang="java">

// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

import java.io.IOException; import java.net.HttpURLConnection; import java.net.Inet4Address; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; /**

* Network utilities.
*/

public class NetUtil {

 /**
  * Resolves hostname and returns ip address as a string.
  */
 public static String resolveHost(String hostname) {
   try {
     InetAddress addr = Inet4Address.getByName(hostname);
     byte[] ipAddr = addr.getAddress();
     StringBuilder ipAddrStr = new StringBuilder(15);
     for (int i = 0; i < ipAddr.length; i++) {
       if (i > 0) {
         ipAddrStr.append(".");
       }
       ipAddrStr.append(ipAddr[i] & 0xFF);
     }
     return ipAddrStr.toString();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }
 /**
  * Resolves string ip address and returns host name as a string.
  */
 public static String resolveIp(String ip) {
   try {
     InetAddress addr = InetAddress.getByName(ip);
     return addr.getHostName();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }
 /**
  * Resolves ip address and returns host name as a string.
  */
 public static String resolveIp(byte[] ip) {
   try {
     InetAddress addr = InetAddress.getByAddress(ip);
     return addr.getHostName();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }

}

 </source>
   
  
 
  



Resolves ip address and returns host name as a string

   <source lang="java">

// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

import java.io.IOException; import java.net.HttpURLConnection; import java.net.Inet4Address; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; /**

* Network utilities.
*/

public class NetUtil {

 /**
  * Resolves hostname and returns ip address as a string.
  */
 public static String resolveHost(String hostname) {
   try {
     InetAddress addr = Inet4Address.getByName(hostname);
     byte[] ipAddr = addr.getAddress();
     StringBuilder ipAddrStr = new StringBuilder(15);
     for (int i = 0; i < ipAddr.length; i++) {
       if (i > 0) {
         ipAddrStr.append(".");
       }
       ipAddrStr.append(ipAddr[i] & 0xFF);
     }
     return ipAddrStr.toString();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }
 /**
  * Resolves string ip address and returns host name as a string.
  */
 public static String resolveIp(String ip) {
   try {
     InetAddress addr = InetAddress.getByName(ip);
     return addr.getHostName();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }
 /**
  * Resolves ip address and returns host name as a string.
  */
 public static String resolveIp(byte[] ip) {
   try {
     InetAddress addr = InetAddress.getByAddress(ip);
     return addr.getHostName();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }

}

 </source>
   
  
 
  



Resolves string ip address and returns host name as a string

   <source lang="java">

// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

import java.io.IOException; import java.net.HttpURLConnection; import java.net.Inet4Address; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; /**

* Network utilities.
*/

public class NetUtil {

 /**
  * Resolves hostname and returns ip address as a string.
  */
 public static String resolveHost(String hostname) {
   try {
     InetAddress addr = Inet4Address.getByName(hostname);
     byte[] ipAddr = addr.getAddress();
     StringBuilder ipAddrStr = new StringBuilder(15);
     for (int i = 0; i < ipAddr.length; i++) {
       if (i > 0) {
         ipAddrStr.append(".");
       }
       ipAddrStr.append(ipAddr[i] & 0xFF);
     }
     return ipAddrStr.toString();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }
 /**
  * Resolves string ip address and returns host name as a string.
  */
 public static String resolveIp(String ip) {
   try {
     InetAddress addr = InetAddress.getByName(ip);
     return addr.getHostName();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }
 /**
  * Resolves ip address and returns host name as a string.
  */
 public static String resolveIp(byte[] ip) {
   try {
     InetAddress addr = InetAddress.getByAddress(ip);
     return addr.getHostName();
   } catch (UnknownHostException uhex) {
     return null;
   }
 }

}

 </source>
   
  
 
  



Retrieve the hostname of an IP Address

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] argv) throws Exception {
   InetAddress addr = InetAddress.getByName("127.0.0.1");
   byte[] ipAddr = new byte[] { 127, 0, 0, 1 };
   addr = InetAddress.getByAddress(ipAddr);
   // Get the host name
   String hostname = addr.getHostName();
   // Get canonical host name
   String canonicalhostname = addr.getCanonicalHostName();
 }

}


 </source>
   
  
 
  



Retrieve the IP address of a hostname

   <source lang="java">
  

import java.net.InetAddress; public class Main {

 public static void main(String[] argv) throws Exception {
   InetAddress addr = InetAddress.getByName("java-tips.org");
   byte[] ipAddr = addr.getAddress();
   // Convert to dot representation
   String ipAddrStr = "";
   for (int i = 0; i < ipAddr.length; i++) {
     if (i > 0) {
       ipAddrStr += ".";
     }
     ipAddrStr += ipAddr[i] & 0xFF;
   }
 }

}


 </source>