Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Obtaining the local Ip is a common requirement scenario, such as business alarm, may bring the faulty machine Ip, convenient to directly go to the log to locate the problem, then the problem comes, how to obtain the machine Ip?

I. IpUtil utility class

1. Basic methods

How do I obtain the machine Ip address? If you know the InetAddress utility class, you can easily write a simple utility class that looks like this

public static String getLocalIP(a) {
    try {
        return InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        throw newRuntimeException(e); }}Copy the code

Is there a problem with the above implementation?

Of course there is no problem, take my machine and Ali server to execute, and there is no problem faithfully output the expected IP

The screenshots after execution are as follows:

The screenshot of Aliyun machine after execution is as follows:

Again, is there really no problem?

  • In some cases, it might return127.0.0.1

You may encounter this problem when executing in a virtual machine, as shown in the screenshot below

2. Advanced version

Make a simple change to obtain the IpV4 address, source code as follows

/** * Uses the address of the first nic as the Intranet ipv4 address instead of returning 127.0.0.1 **@return* /
public static String getLocalIpByNetcard(a) {
    try {
        for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) {
            NetworkInterface item = e.nextElement();
            for (InterfaceAddress address : item.getInterfaceAddresses()) {
                if(item.isLoopback() || ! item.isUp()) {continue;
                }
                if (address.getAddress() instanceof Inet4Address) {
                    Inet4Address inet4Address = (Inet4Address) address.getAddress();
                    returninet4Address.getHostAddress(); }}}return InetAddress.getLocalHost().getHostAddress();
    } catch (SocketException | UnknownHostException e) {
        throw newRuntimeException(e); }}Copy the code

Test again, and the output is as follows

3. Complete tool classes

import java.net.*;
import java.util.Enumeration;

public class IpUtil {
    public static final String DEFAULT_IP = "127.0.0.1";

    /** * Uses the address of the first nic as the Intranet ipv4 address instead of returning 127.0.0.1 **@return* /
    public static String getLocalIpByNetcard(a) {
        try {
            for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) {
                NetworkInterface item = e.nextElement();
                for (InterfaceAddress address : item.getInterfaceAddresses()) {
                    if(item.isLoopback() || ! item.isUp()) {continue;
                    }
                    if (address.getAddress() instanceof Inet4Address) {
                        Inet4Address inet4Address = (Inet4Address) address.getAddress();
                        returninet4Address.getHostAddress(); }}}return InetAddress.getLocalHost().getHostAddress();
        } catch (SocketException | UnknownHostException e) {
            throw newRuntimeException(e); }}public static String getLocalIP(a) {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw newRuntimeException(e); }}}Copy the code

II. The other

1. A gray Blog:liuyueyi.github.io/hexblog

A gray personal blog, recording all the study and work in the blog, welcome everyone to go to stroll

2. Statement

As far as the letter is not as good as, has been the content, purely one’s own words, because of the limited personal ability, it is hard to avoid omissions and mistakes, such as finding bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Micro Blog address: Small Gray Blog
  • QQ: a gray /3302797840
  • Wechat official account: One Grey Blog