集册 Java实例教程 获取本地IP地址

获取本地IP地址

欢马劈雪     最近更新时间:2020-01-02 10:19:05

453
获取本地IP地址


import java.net.InetAddress;
/**
来 自 N o w J a v a . c o m - 时代Java
**/

import java.net.NetworkInterface;

import java.net.SocketException;

import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;

import org.apache.log4j.Logger;


public class Main{

    public static void main(String[] argv) throws Exception{

        System.out.println(getLocalAddresses());

    }/*nowjava.com - 时  代  Java*/

    private static final Logger LOGGER = Logger

            .getLogger(HostAddressUtil.class);

    public static List<String> getLocalAddresses() {

        List<String> list = new ArrayList<String>();

        Enumeration<NetworkInterface> interfaceList = null;

        try {

            interfaceList = NetworkInterface.getNetworkInterfaces();

        } catch (SocketException ex) {

            LOGGER.error("Error when getting local network interfaces", ex);

        }

        if (interfaceList != null) {

            while (interfaceList.hasMoreElements()) {

                NetworkInterface face = (NetworkInterface) interfaceList

                        .nextElement();

                Enumeration<InetAddress> addressList = face

                        .getInetAddresses();

                if (addressList == null) {

                    
展开阅读全文