Here you can find the source of getIP()
Parameter | Description |
---|---|
SocketException | an exception |
public static InetAddress getIP() throws SocketException
//package com.java2s; /*/*from ww w.j a v a2 s . c o m*/ * This work is licensed under the Creative Commons Attribution 3.0 Unported * License. To view a copy of this license, visit * http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative * Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. */ import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class Main { private static InetAddress _ip; /** * Get an IP. * * @return * @throws SocketException */ public static InetAddress getIP() throws SocketException { if (_ip != null) { return _ip; } Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); NetworkInterface ni; while (nis.hasMoreElements()) { ni = nis.nextElement(); if (!ni.isLoopback()/*not loopback*/ && ni.isUp()/*it works now*/) { for (InterfaceAddress ia : ni.getInterfaceAddresses()) { //filter for ipv4/ipv6 if (ia.getAddress().getAddress().length == 4) { //4 for ipv4, 16 for ipv6 _ip = ia.getAddress(); return _ip; } } } } return null; } }