Java IP Address Get getIp()

Here you can find the source of getIp()

Description

Gets my IP as String.

License

Open Source License

Declaration

public static String getIp() 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class Main {
    /**//from ww  w  .  j  a  v  a  2s  .  c o  m
     * Gets my IP as String. Returns null if not possible
     */
    public static String getIp() {
        try {
            List<String> ips = new ArrayList<String>();
            Enumeration<NetworkInterface> interfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface current = interfaces.nextElement();
                if (current.isUp() && !current.isLoopback()
                        && !current.isVirtual()) {
                    Enumeration<InetAddress> addresses = current
                            .getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress current_addr = addresses.nextElement();
                        if (!current_addr.isLoopbackAddress()
                                && current_addr instanceof Inet4Address) {
                            ips.add(current_addr.getHostAddress());
                        }
                    }
                }
            }
            // TODO egrande: review this ip resolution
            return ips.get(0);
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
            return null;
        }
    }
}

Related

  1. getIntfFromLabelAdva(int n, Inet4Address ip)
  2. getIntranetIp()
  3. getIP()
  4. getIp()
  5. getIP()
  6. getIp()
  7. getIp()
  8. getIp()
  9. getIp()