KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > NetUtil


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.util;
4
5 import jodd.io.StreamUtil;
6
7 import java.io.IOException JavaDoc;
8 import java.net.HttpURLConnection JavaDoc;
9 import java.net.Inet4Address JavaDoc;
10 import java.net.InetAddress JavaDoc;
11 import java.net.URL JavaDoc;
12 import java.net.UnknownHostException JavaDoc;
13
14 /**
15  * Network utilities.
16  */

17 public class NetUtil {
18
19     /**
20      * Resolves hostname and returns ip address as a string.
21      */

22     public static String JavaDoc resolveHost(String JavaDoc hostname) {
23         try {
24             InetAddress JavaDoc addr = Inet4Address.getByName(hostname);
25             byte[] ipAddr = addr.getAddress();
26             StringBuffer JavaDoc ipAddrStr = new StringBuffer JavaDoc(15);
27             for (int i = 0; i < ipAddr.length; i++) {
28                 if (i > 0) {
29                     ipAddrStr.append('.');
30                 }
31                 ipAddrStr.append(ipAddr[i] & 0xFF);
32             }
33             return ipAddrStr.toString();
34         } catch (UnknownHostException JavaDoc uhex) {
35             return null;
36         }
37     }
38
39     /**
40      * Resolves string ip address and returns host name as a string.
41      */

42     public static String JavaDoc resolveIp(String JavaDoc ip) {
43         try {
44             InetAddress JavaDoc addr = InetAddress.getByName(ip);
45             return addr.getHostName();
46         } catch (UnknownHostException JavaDoc uhex) {
47             return null;
48         }
49     }
50
51     /**
52      * Resolves ip address and returns host name as a string.
53      */

54     public static String JavaDoc resolveIp(byte[] ip) {
55         try {
56             InetAddress JavaDoc addr = InetAddress.getByAddress(ip);
57             return addr.getHostName();
58         } catch (UnknownHostException JavaDoc uhex) {
59             return null;
60         }
61     }
62
63     // ---------------------------------------------------------------- download
64

65     /**
66      * Download resource from URL.
67      */

68     public static byte[] download(String JavaDoc url) throws IOException JavaDoc {
69         HttpURLConnection JavaDoc conection = (HttpURLConnection JavaDoc)((new URL JavaDoc(url).openConnection()));
70         return StreamUtil.readBytes(conection.getInputStream());
71     }
72 }
Popular Tags