Here you can find the source of getLocalIpAddress()
Parameter | Description |
---|---|
UnknownHostException | an exception |
public static InetAddress getLocalIpAddress() throws UnknownHostException
//package com.java2s; /*/*from www . ja v a2 s .c om*/ * Copyright (C) 2016 Maximilian Pawlidi * * Licensed 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.net.InetAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Enumeration; public class Main { /** * * @return * @throws UnknownHostException */ public static InetAddress getLocalIpAddress() throws UnknownHostException { try { InetAddress localAddress = null; // load all existed network interfaces for (Enumeration<?> networkInterfaces = NetworkInterface .getNetworkInterfaces(); networkInterfaces .hasMoreElements();) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces .nextElement(); for (Enumeration<?> ipAddresses = networkInterface .getInetAddresses(); ipAddresses.hasMoreElements();) { InetAddress ipAddress = (InetAddress) ipAddresses .nextElement(); if (!ipAddress.isLoopbackAddress()) { if (ipAddress.isSiteLocalAddress()) { return ipAddress; } else if (localAddress == null) { localAddress = ipAddress; } } } } if (localAddress != null) { return localAddress; } // try to get localhost address localAddress = InetAddress.getLocalHost(); if (localAddress == null) { throw new UnknownHostException( "Could not load localhost ip address"); } return localAddress; } catch (Exception e) { UnknownHostException unknownHostException = new UnknownHostException( "Could not load localhost ip address " + e); unknownHostException.initCause(e); throw unknownHostException; } } }