Java IP Address Get getIpAddress()

Here you can find the source of getIpAddress()

Description

get Ip Address

License

Apache License

Declaration

public static String getIpAddress() 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static String getIpAddress() {
        String ip = null;/*  w  w  w . jav  a 2s  .  com*/
        try {
            Enumeration<NetworkInterface> er = NetworkInterface
                    .getNetworkInterfaces();
            while (er.hasMoreElements()) {
                NetworkInterface ni = er.nextElement();
                if (ni.getName().startsWith("eth")
                        || ni.getName().startsWith("bond")) {
                    List<InterfaceAddress> list = ni
                            .getInterfaceAddresses();
                    for (InterfaceAddress interfaceAddress : list) {
                        InetAddress address = interfaceAddress.getAddress();
                        if (address instanceof Inet4Address) {
                            ip = address.getHostAddress();
                            break;
                        }
                    }
                }
                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {
        }
        if (ip == null) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
            }
        }
        return ip;
    }
}

Related

  1. getIpAddress()
  2. getIpAddress()
  3. getIPAddress()
  4. getIPAddress()
  5. getIPAddress()
  6. getIpAddress()
  7. getIPAddress(boolean useIPv4)
  8. getIPAddress(final String hostName)
  9. getIPAddress(NetworkInterface e)