Here you can find the source of getLocalAddr()
Parameter | Description |
---|---|
SocketException | local IPV4 address. |
public static InetAddress getLocalAddr() throws SocketException
//package com.java2s; /*//from ww w . j a va2 s . com * Copyrigth (C) 2010 Henrik Baastrup. * * Licensed under the GNU Lesser General Public License version 3; * you may not use this file except in compliance with the License. * You should have received a copy of the license together with this * file but can obtain a copy of the License at: * * http://www.gnu.org/licenses/lgpl-3.0.txt * * 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.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class Main { /** * Will try to find the local IP V4 address there is not the loopback address * @return * @throws SocketException local IPV4 address. */ public static InetAddress getLocalAddr() throws SocketException { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface dev = interfaces.nextElement(); String devName = dev.getDisplayName(); Enumeration<InetAddress> addresses = dev.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet6Address) continue; //STUN might not be intresting with an IP V6 address String addrStr = addr.getHostAddress(); if (addrStr.startsWith("127.")) continue; return addr; } } return null; } }