Here you can find the source of getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
Parameter | Description |
---|---|
preferIpv4 | If you want the Internet Protocol version 4 (IPv4) address, this value must be true . |
preferIPv6 | If you want the Internet Protocol version 6 (IPv6) address, this value must be true . If the preferIpv4 is set to true , this value is ignored |
Parameter | Description |
---|---|
SocketException | If an I/O error occurs. |
public static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException
//package com.java2s; /*//from ww w. java 2 s . co m * Copyright to the original author or authors * * 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.*; import java.util.Enumeration; public class Main { /** * Get the first non-loopback address. * * @param preferIpv4 If you want the Internet Protocol version 4 (IPv4) address, this value must be {@code true}. * @param preferIPv6 If you want the Internet Protocol version 6 (IPv6) address, this value must be {@code true}. * If the {@code preferIpv4} is set to {@code true}, this value is ignored * @return The first non loopback address or {@code null} if there are no non-loopback addresses. * @throws SocketException If an I/O error occurs. */ public static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException { Enumeration en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface i = (NetworkInterface) en.nextElement(); for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr = (InetAddress) en2.nextElement(); if (!addr.isLoopbackAddress()) { if (addr instanceof Inet4Address) { if (preferIPv6) { continue; } if (preferIpv4) return addr; } if (addr instanceof Inet6Address) { if (preferIpv4) { continue; } if (preferIPv6) return addr; } else return addr; } } } return null; } }