Here you can find the source of getLocalAddressStrings()
Parameter | Description |
---|---|
UnknownHostException | If the localhost name cannot be resolved. |
SocketException | an exception |
public static String[] getLocalAddressStrings() throws UnknownHostException, SocketException
//package com.java2s; /*//from ww w . j a v a 2s. c om * (C) Copyright IBM Corp. 2011 * * LICENSE: Eclipse Public License v1.0 * http://www.eclipse.org/legal/epl-v10.html */ import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class Main { /** Reference to the local host address */ private static InetAddress localAddress = null; /** * Return all valid IP addresses for this local host. * Note: List can include both IPv4 and IPv6 addresses. * * @return a list of addresses represented as string or null in the event of an error. * @throws UnknownHostException If the localhost name cannot be resolved. * @throws SocketException */ public static String[] getLocalAddressStrings() throws UnknownHostException, SocketException { String[] localAddressStrings = null; if (localAddress != null) { InetAddress[] allMyAddresses = getLocalAddresses(); if (allMyAddresses != null) { localAddressStrings = new String[allMyAddresses.length]; for (int y = 0; y < allMyAddresses.length; y++) { localAddressStrings[y] = allMyAddresses[y].getHostAddress(); } } } return localAddressStrings; } /** * Return all valid IP addresses for this local host. * Note: List can include both IPv4 and IPv6 addresses. * * @return a list of InetAddress objects or null in the event of an error. * @throws UnknownHostException If the localhost name cannot be resolved. * @throws SocketException if an error occurs getting the list of local interfaces */ public static InetAddress[] getLocalAddresses() throws UnknownHostException, SocketException { List<InetAddress> allMyAddresses = new ArrayList<InetAddress>(); if (localAddress != null) { Enumeration<NetworkInterface> localInterfaces = getLocalInterfaces(); Enumeration<InetAddress> interfaceAddresses = null; while (localInterfaces.hasMoreElements()) { /* get the set of addresses for each interface */ interfaceAddresses = localInterfaces.nextElement().getInetAddresses(); while (interfaceAddresses.hasMoreElements()) { allMyAddresses.add(interfaceAddresses.nextElement()); } } // allMyAddresses = InetAddress.getAllByName(localAddress.getHostName()); } InetAddress[] addresses = allMyAddresses.toArray(new InetAddress[allMyAddresses.size()]); return addresses; } /** * Return the set of network interfaces for the local host. * * @return an enumeration of the interfaces or null otherwise. * @throws SocketException if an error occurs getting the interface list. */ public static Enumeration<NetworkInterface> getLocalInterfaces() throws SocketException { return NetworkInterface.getNetworkInterfaces(); } }