Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class Main {
    public static String getIpAddress(boolean alwaysGetWifi) {

        try {
            Enumeration<NetworkInterface> enmNetI = NetworkInterface.getNetworkInterfaces();
            while (enmNetI.hasMoreElements()) {
                NetworkInterface networkInterface = enmNetI.nextElement();
                boolean b = alwaysGetWifi
                        ? networkInterface.getDisplayName().equals("wlan0")
                                || networkInterface.getDisplayName().equals("eth0")
                        : true;
                if (b) {
                    Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();
                    while (inetAddressEnumeration.hasMoreElements()) {
                        InetAddress inetAddress = inetAddressEnumeration.nextElement();
                        if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                            return "net name is " + networkInterface.getDisplayName() + ",ip is "
                                    + inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        return "";
    }
}