Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKBJavaConnector/ECJClient/src/ec/util/LocalHost.java @ 6152

Last change on this file since 6152 was 6152, checked in by bfarka, 13 years ago

added ecj and custom statistics to communicate with the okb services #1441

File size: 15.1 KB
Line 
1package ec.util;
2
3import java.net.*;
4import java.util.*;
5
6/**
7 * Modified from <a href="http://mail-archives.apache.org/mod_mbox/jakarta-jcs-dev/200803.mbox/%3C1066089445.1204637680849.JavaMail.jira@brutus%3E">
8 * apache mail-archives</a>.
9 *
10 * This code was published in the public domain, but I believe it was probably intended to be
11 * distributed under the Apache license, like the rest of the Jakarta code.  That license is
12 * listed at the end of this file.
13 *
14 */
15 
16public class LocalHost
17    {
18    /**
19     * Returns an <code>InetAddress</code> object encapsulating what is most
20     * likely the machine's LAN IP address. <p/> This method is intended for use
21     * as a replacement of JDK method <code>InetAddress.getLocalHost</code>,
22     * because that method is ambiguous on Linux systems. Linux systems
23     * enumerate the loopback network interface the same way as regular LAN
24     * network interfaces, but the JDK <code>InetAddress.getLocalHost</code>
25     * method does not specify the algorithm used to select the address returned
26     * under such circumstances, and will often return the loopback address,
27     * which is not valid for network communication. Details <a
28     * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037"
29     * >here</a>. <p/> This method will scan all IP addresses on all network
30     * interfaces on the host machine to determine the IP address most likely to
31     * be the machine's LAN address. If the machine has multiple IP addresses,
32     * this method will prefer a site-local IP address (e.g. 192.168.x.x or
33     * 10.10.x.x, usually IPv4) if the machine has one (and will return the
34     * first site-local address if the machine has more than one), but if the
35     * machine does not hold a site-local address, this method will return
36     * simply the first non-loopback address found (IPv4 or IPv6). <p/> If this
37     * method cannot find a non-loopback address using this selection algorithm,
38     * it will fall back to calling and returning the result of JDK method
39     * <code>InetAddress.getLocalHost</code>. <p/>
40     *
41     * @throws UnknownHostException
42     *             If the LAN address of the machine cannot be found.
43     */
44    public static InetAddress getLocalHost() throws UnknownHostException
45        {
46        try
47            {
48            InetAddress candidateAddress = null;
49            // Iterate all NICs (network interface cards)...
50            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();)
51                {
52                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
53                // Iterate all IP addresses assigned to each card...
54                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();)
55                    {
56                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
57                    if (!inetAddr.isLoopbackAddress())
58                        {
59                        if (inetAddr.isSiteLocalAddress()) return inetAddr;  // Found non-loopback site-local address.
60
61                        // Found non-loopback address, but not necessarily site-local.
62                        // Store it as a candidate to be returned if site-local address is not subsequently found...
63                        // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
64                        // only the first. For subsequent iterations, candidate will be non-null.
65                        else if (candidateAddress == null) candidateAddress = inetAddr;
66                        }
67                    }
68                }
69            // We did not find a site-local address, but we found some other non-loopback address.
70            // Server might have a non-site-local address assigned to its NIC (or it might be running
71            // IPv6 which deprecates the "site-local" concept).
72            // Return this non-loopback candidate address...
73            if (candidateAddress != null) return candidateAddress;
74
75            // At this point, we did not find a non-loopback address.
76            // Fall back to returning whatever InetAddress.getLocalHost() returns...
77            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
78            if (jdkSuppliedAddress == null)
79                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
80            return jdkSuppliedAddress;
81            }
82        catch (Exception e)
83            {
84            UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
85            unknownHostException.initCause(e);
86            throw unknownHostException;
87            }
88        }
89    }
90
91
92
93/*
94
95  Apache License
96  Version 2.0, January 2004
97  http://www.apache.org/licenses/
98
99  TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
100
101  1. Definitions.
102
103  "License" shall mean the terms and conditions for use, reproduction,
104  and distribution as defined by Sections 1 through 9 of this document.
105
106  "Licensor" shall mean the copyright owner or entity authorized by
107  the copyright owner that is granting the License.
108
109  "Legal Entity" shall mean the union of the acting entity and all
110  other entities that control, are controlled by, or are under common
111  control with that entity. For the purposes of this definition,
112  "control" means (i) the power, direct or indirect, to cause the
113  direction or management of such entity, whether by contract or
114  otherwise, or (ii) ownership of fifty percent (50%) or more of the
115  outstanding shares, or (iii) beneficial ownership of such entity.
116
117  "You" (or "Your") shall mean an individual or Legal Entity
118  exercising permissions granted by this License.
119
120  "Source" form shall mean the preferred form for making modifications,
121  including but not limited to software source code, documentation
122  source, and configuration files.
123
124  "Object" form shall mean any form resulting from mechanical
125  transformation or translation of a Source form, including but
126  not limited to compiled object code, generated documentation,
127  and conversions to other media types.
128
129  "Work" shall mean the work of authorship, whether in Source or
130  Object form, made available under the License, as indicated by a
131  copyright notice that is included in or attached to the work
132  (an example is provided in the Appendix below).
133
134  "Derivative Works" shall mean any work, whether in Source or Object
135  form, that is based on (or derived from) the Work and for which the
136  editorial revisions, annotations, elaborations, or other modifications
137  represent, as a whole, an original work of authorship. For the purposes
138  of this License, Derivative Works shall not include works that remain
139  separable from, or merely link (or bind by name) to the interfaces of,
140  the Work and Derivative Works thereof.
141
142  "Contribution" shall mean any work of authorship, including
143  the original version of the Work and any modifications or additions
144  to that Work or Derivative Works thereof, that is intentionally
145  submitted to Licensor for inclusion in the Work by the copyright owner
146  or by an individual or Legal Entity authorized to submit on behalf of
147  the copyright owner. For the purposes of this definition, "submitted"
148  means any form of electronic, verbal, or written communication sent
149  to the Licensor or its representatives, including but not limited to
150  communication on electronic mailing lists, source code control systems,
151  and issue tracking systems that are managed by, or on behalf of, the
152  Licensor for the purpose of discussing and improving the Work, but
153  excluding communication that is conspicuously marked or otherwise
154  designated in writing by the copyright owner as "Not a Contribution."
155
156  "Contributor" shall mean Licensor and any individual or Legal Entity
157  on behalf of whom a Contribution has been received by Licensor and
158  subsequently incorporated within the Work.
159
160  2. Grant of Copyright License. Subject to the terms and conditions of
161  this License, each Contributor hereby grants to You a perpetual,
162  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
163  copyright license to reproduce, prepare Derivative Works of,
164  publicly display, publicly perform, sublicense, and distribute the
165  Work and such Derivative Works in Source or Object form.
166
167  3. Grant of Patent License. Subject to the terms and conditions of
168  this License, each Contributor hereby grants to You a perpetual,
169  worldwide, non-exclusive, no-charge, royalty-free, irrevocable
170  (except as stated in this section) patent license to make, have made,
171  use, offer to sell, sell, import, and otherwise transfer the Work,
172  where such license applies only to those patent claims licensable
173  by such Contributor that are necessarily infringed by their
174  Contribution(s) alone or by combination of their Contribution(s)
175  with the Work to which such Contribution(s) was submitted. If You
176  institute patent litigation against any entity (including a
177  cross-claim or counterclaim in a lawsuit) alleging that the Work
178  or a Contribution incorporated within the Work constitutes direct
179  or contributory patent infringement, then any patent licenses
180  granted to You under this License for that Work shall terminate
181  as of the date such litigation is filed.
182
183  4. Redistribution. You may reproduce and distribute copies of the
184  Work or Derivative Works thereof in any medium, with or without
185  modifications, and in Source or Object form, provided that You
186  meet the following conditions:
187
188  (a) You must give any other recipients of the Work or
189  Derivative Works a copy of this License; and
190
191  (b) You must cause any modified files to carry prominent notices
192  stating that You changed the files; and
193
194  (c) You must retain, in the Source form of any Derivative Works
195  that You distribute, all copyright, patent, trademark, and
196  attribution notices from the Source form of the Work,
197  excluding those notices that do not pertain to any part of
198  the Derivative Works; and
199
200  (d) If the Work includes a "NOTICE" text file as part of its
201  distribution, then any Derivative Works that You distribute must
202  include a readable copy of the attribution notices contained
203  within such NOTICE file, excluding those notices that do not
204  pertain to any part of the Derivative Works, in at least one
205  of the following places: within a NOTICE text file distributed
206  as part of the Derivative Works; within the Source form or
207  documentation, if provided along with the Derivative Works; or,
208  within a display generated by the Derivative Works, if and
209  wherever such third-party notices normally appear. The contents
210  of the NOTICE file are for informational purposes only and
211  do not modify the License. You may add Your own attribution
212  notices within Derivative Works that You distribute, alongside
213  or as an addendum to the NOTICE text from the Work, provided
214  that such additional attribution notices cannot be construed
215  as modifying the License.
216
217  You may add Your own copyright statement to Your modifications and
218  may provide additional or different license terms and conditions
219  for use, reproduction, or distribution of Your modifications, or
220  for any such Derivative Works as a whole, provided Your use,
221  reproduction, and distribution of the Work otherwise complies with
222  the conditions stated in this License.
223
224  5. Submission of Contributions. Unless You explicitly state otherwise,
225  any Contribution intentionally submitted for inclusion in the Work
226  by You to the Licensor shall be under the terms and conditions of
227  this License, without any additional terms or conditions.
228  Notwithstanding the above, nothing herein shall supersede or modify
229  the terms of any separate license agreement you may have executed
230  with Licensor regarding such Contributions.
231
232  6. Trademarks. This License does not grant permission to use the trade
233  names, trademarks, service marks, or product names of the Licensor,
234  except as required for reasonable and customary use in describing the
235  origin of the Work and reproducing the content of the NOTICE file.
236
237  7. Disclaimer of Warranty. Unless required by applicable law or
238  agreed to in writing, Licensor provides the Work (and each
239  Contributor provides its Contributions) on an "AS IS" BASIS,
240  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
241  implied, including, without limitation, any warranties or conditions
242  of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
243  PARTICULAR PURPOSE. You are solely responsible for determining the
244  appropriateness of using or redistributing the Work and assume any
245  risks associated with Your exercise of permissions under this License.
246
247  8. Limitation of Liability. In no event and under no legal theory,
248  whether in tort (including negligence), contract, or otherwise,
249  unless required by applicable law (such as deliberate and grossly
250  negligent acts) or agreed to in writing, shall any Contributor be
251  liable to You for damages, including any direct, indirect, special,
252  incidental, or consequential damages of any character arising as a
253  result of this License or out of the use or inability to use the
254  Work (including but not limited to damages for loss of goodwill,
255  work stoppage, computer failure or malfunction, or any and all
256  other commercial damages or losses), even if such Contributor
257  has been advised of the possibility of such damages.
258
259  9. Accepting Warranty or Additional Liability. While redistributing
260  the Work or Derivative Works thereof, You may choose to offer,
261  and charge a fee for, acceptance of support, warranty, indemnity,
262  or other liability obligations and/or rights consistent with this
263  License. However, in accepting such obligations, You may act only
264  on Your own behalf and on Your sole responsibility, not on behalf
265  of any other Contributor, and only if You agree to indemnify,
266  defend, and hold each Contributor harmless for any liability
267  incurred by, or claims asserted against, such Contributor by reason
268  of your accepting any such warranty or additional liability.
269
270  END OF TERMS AND CONDITIONS
271
272  APPENDIX: How to apply the Apache License to your work.
273
274  To apply the Apache License to your work, attach the following
275  boilerplate notice, with the fields enclosed by brackets "[]"
276  replaced with your own identifying information. (Don't include
277  the brackets!)  The text should be enclosed in the appropriate
278  comment syntax for the file format. We also recommend that a
279  file or class name and description of purpose be included on the
280  same "printed page" as the copyright notice for easier
281  identification within third-party archives.
282
283  Copyright [yyyy] [name of copyright owner]
284
285  Licensed under the Apache License, Version 2.0 (the "License");
286  you may not use this file except in compliance with the License.
287  You may obtain a copy of the License at
288
289  http://www.apache.org/licenses/LICENSE-2.0
290
291  Unless required by applicable law or agreed to in writing, software
292  distributed under the License is distributed on an "AS IS" BASIS,
293  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
294  See the License for the specific language governing permissions and
295  limitations under the License.
296*/
Note: See TracBrowser for help on using the repository browser.