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

从NetworkInterface获取IP地址

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

705
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
从NetworkInterface获取IP地址


//package com.nowjava;/** 来自 N o w  J a v a  . c o m**/

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.util.Enumeration;


public class Main {

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

        System.out.println(getInetAddress());

    }


    private static String getInetAddress() {

        try {

            Enumeration<NetworkInterface> interfaces = NetworkInterface

                    .getNetworkInterfaces();/*N o w  J a v a  . c o m 提 供*/

            InetAddress address = null;

            while (interfaces.hasMoreElements()) {

                NetworkInterface ni = interfaces.nextElement();

                Enumeration<InetAddress> addresses = ni.getInetAddresses();

                while (addresses.hasMoreElements()) {

                    address = addresses.nextElement();

                    if (!address.isLoopbackAddress()

                            && address.getHostAddress().indexOf(":") == -1) {

                        return address.getHost
展开阅读全文