KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > petals > util > NetworkUtil


1 /**
2  * PETALS - PETALS Services Platform.
3  * Copyright (c) 2005 EBM Websourcing, http://www.ebmwebsourcing.com/
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * -------------------------------------------------------------------------
19  * $Id$
20  * -------------------------------------------------------------------------
21  */

22 package org.objectweb.petals.util;
23
24 import java.io.DataInputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.net.InetAddress JavaDoc;
27 import java.net.NetworkInterface JavaDoc;
28 import java.net.SocketException JavaDoc;
29 import java.util.Enumeration JavaDoc;
30
31 /**
32  * Network utilities
33  *
34  * @author Christophe Hamerling - EBM WebSourcing
35  *
36  */

37 public class NetworkUtil {
38
39     /** The IPIv4 loopback address */
40     public static String JavaDoc IPV4_LOOPBACK_ADDRESS = "127.0.0.1";
41     
42     /**
43      * Creates a new instance of NetworkUtil
44      */

45     private NetworkUtil() {
46     }
47
48     /**
49      * Get the IPv4 address of current host. The loopback address is returned if
50      * no other interface has been found.
51      *
52      * @return
53      * @throws SocketException
54      */

55     public static String JavaDoc getIPv4Address() throws SocketException JavaDoc {
56         Enumeration JavaDoc<NetworkInterface JavaDoc> e = NetworkInterface
57             .getNetworkInterfaces();
58
59         while (e.hasMoreElements()) {
60             NetworkInterface JavaDoc netItf = e.nextElement();
61             Enumeration JavaDoc<InetAddress JavaDoc> addresses = netItf.getInetAddresses();
62
63             while (addresses.hasMoreElements()) {
64                 InetAddress JavaDoc ip = addresses.nextElement();
65                 if (!ip.isLoopbackAddress() && isIPv4(ip.getHostAddress())) {
66                     return ip.getHostAddress();
67                 }
68             }
69         }
70         return NetworkUtil.IPV4_LOOPBACK_ADDRESS;
71     }
72
73     /**
74      * Resolve the "localhost" IP address. Call the system command "ipconfig" or
75      * "ifconfig" and parse the result to extract the IP.
76      *
77      * @return the real IP address of the machine, or 127.0.0.1 if the system
78      * call fails or if not parsed.
79      */

80     protected static String JavaDoc getAddressFromSystemCall() {
81         String JavaDoc host = IPV4_LOOPBACK_ADDRESS;
82         String JavaDoc hostIP = "";
83         String JavaDoc os = System.getProperty("os.name").toLowerCase();
84
85         String JavaDoc command = "/sbin/ifconfig";
86
87         if (os.indexOf("windows") != -1) {
88             // We are on Windows
89
command = "ipconfig";
90
91         } else if (os.indexOf("linux") != -1) {
92             // We are on Linux
93
command = "/sbin/ifconfig";
94
95         } else if (os.indexOf("mac") != -1) {
96             // We are on a Mac :)
97
command = "ifconfig";
98         }
99
100         // Execute the command
101
try {
102             Process JavaDoc process = Runtime.getRuntime().exec(command);
103             try {
104                 process.waitFor();
105             } catch (InterruptedException JavaDoc e) {
106                 // Do nothing
107
}
108             DataInputStream JavaDoc dis = new DataInputStream JavaDoc(process.getInputStream());
109             byte[] content = new byte[dis.available()];
110             dis.readFully(content);
111             String JavaDoc output = new String JavaDoc(content);
112
113             // search address from result data
114
if (os.indexOf("windows") != -1 && output.length() > 45) {
115                 hostIP = getAddressFromWindowsSystemCallResult(output);
116             } else if (os.indexOf("linux") != -1) {
117                 hostIP = getAddressFromLinuxSystemCallResult(output);
118             } else if (os.indexOf("mac") != -1) {
119                 hostIP = getAddressFromMacSystemCallResult(output);
120             } else {
121                 // other platforms ?
122
}
123
124         } catch (IOException JavaDoc e) {
125             // Do nothing
126
}
127
128         // If connection cable is disconnected, the retrieved IP is a
129
// bad IP ("Media disconnected" for exemple), so we have to test
130
// if the retrieved IP starts with a number.
131
if (hostIP.charAt(0) >= '0' && hostIP.charAt(0) <= '9') {
132             host = hostIP;
133         }
134
135         return host.trim();
136     }
137
138     /**
139      *
140      * @param output
141      * @return
142      */

143     private static String JavaDoc getAddressFromWindowsSystemCallResult(String JavaDoc output) {
144         String JavaDoc hostIP = "";
145         // We are on Windows, and the ipconfig command return a
146
// String with information
147
// (size >45 char, otherwise, pb with IPCONFIG command)
148
if (output.indexOf("IP") > -1) {
149             hostIP = output.substring(output.indexOf(": ", output.indexOf("IP",
150                 output.indexOf("IP") + 10)) + 2, output.indexOf(": ", output
151                 .indexOf("IP", output.indexOf("IP") + 10)) + 15);
152
153         }
154         return hostIP;
155     }
156
157     /**
158      * TODO
159      *
160      * @param output
161      * @return
162      */

163     private static String JavaDoc getAddressFromMacSystemCallResult(String JavaDoc output) {
164         return "";
165     }
166
167     /**
168      *
169      * @param output
170      * @return
171      */

172     private static String JavaDoc getAddressFromLinuxSystemCallResult(String JavaDoc output) {
173         String JavaDoc hostIP = "";
174         // We are on Linux
175
if (output.indexOf("lo") > -1) {
176             // Remove the loopback part
177
output = output.substring(0, output.indexOf("lo"))
178                 + output.substring(output.indexOf("\n", output.indexOf(")",
179                     output.indexOf("lo"))), output.length());
180         }
181         if (output.indexOf("inet addr:") > -1) {
182             // Extract the first ip address
183
hostIP = output.substring(output.indexOf("inet addr:") + 10, output
184                 .indexOf(" ", output.indexOf("inet addr:") + 10));
185         } else if (output.indexOf("inet adr:") > -1) {
186             // Extract the first ip address
187
hostIP = output.substring(output.indexOf("inet adr:") + 9, output
188                 .indexOf(" ", output.indexOf("inet adr:") + 10));
189         }
190         return hostIP;
191     }
192
193     /**
194      *
195      * @param hostAddress
196      * @return
197      */

198     public static boolean isIPv4(String JavaDoc hostAddress) {
199         return hostAddress.split("[.]").length == 4;
200     }
201
202 }
203
Popular Tags