|
| 1 | +/* |
| 2 | +* JavaBeanStack FrameWork |
| 3 | +* |
| 4 | +* Copyright (C) 2017 - 2018 Jorge Enciso |
| 5 | +* Email: jorge.enciso.r@gmail.com |
| 6 | +* jenciso@javabeanstack.org |
| 7 | +* |
| 8 | +* This library is free software; you can redistribute it and/or |
| 9 | +* modify it under the terms of the GNU Lesser General Public |
| 10 | +* License as published by the Free Software Foundation; either |
| 11 | +* version 3 of the License, or (at your option) any later version. |
| 12 | +* |
| 13 | +* This library is distributed in the hope that it will be useful, |
| 14 | +* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 16 | +* Lesser General Public License for more details. |
| 17 | +* |
| 18 | +* You should have received a copy of the GNU Lesser General Public |
| 19 | +* License along with this library; if not, write to the Free Software |
| 20 | +* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, |
| 21 | +* MA 02110-1301 USA |
| 22 | + */ |
| 23 | +package org.javabeanstack.util; |
| 24 | + |
| 25 | +import java.net.InetAddress; |
| 26 | +import java.net.NetworkInterface; |
| 27 | +import java.net.SocketException; |
| 28 | +import java.net.UnknownHostException; |
| 29 | +import java.util.Enumeration; |
| 30 | + |
| 31 | +/** |
| 32 | + * |
| 33 | + * @author Jorge Enciso |
| 34 | + */ |
| 35 | +public class Network { |
| 36 | + |
| 37 | + public static String getLocalIpAdress() { |
| 38 | + String result = ""; |
| 39 | + try { |
| 40 | + InetAddress address = InetAddress.getLocalHost(); |
| 41 | + result = address.getHostAddress(); |
| 42 | + } catch (UnknownHostException ex) { |
| 43 | + System.out.println("Could not find IP address for this host"); |
| 44 | + } |
| 45 | + if (result.isEmpty()) { |
| 46 | + try { |
| 47 | + Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); |
| 48 | + while (networkInterfaces.hasMoreElements()) { |
| 49 | + NetworkInterface networkInterface = networkInterfaces.nextElement(); |
| 50 | + if (!networkInterface.isUp()) { |
| 51 | + continue; |
| 52 | + } |
| 53 | + if (networkInterface.isLoopback()) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); |
| 57 | + while (addresses.hasMoreElements()) { |
| 58 | + InetAddress address = addresses.nextElement(); |
| 59 | + if (address.isLinkLocalAddress()) { |
| 60 | + continue; |
| 61 | + } |
| 62 | + if (address.isSiteLocalAddress()) { |
| 63 | + result = address.getHostAddress(); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + } catch (SocketException ex) { |
| 68 | + System.out.println("Could not find IP address for this host"); |
| 69 | + } |
| 70 | + } |
| 71 | + return result; |
| 72 | + } |
| 73 | +} |
0 commit comments