java如何获取当前登录ip

Python015

java如何获取当前登录ip,第1张

第一种:获取本机的IP

Enumeration<NetworkInterface>

netInterfaces

=

null

try

{

netInterfaces

=

NetworkInterface.getNetworkInterfaces()

while

(netInterfaces.hasMoreElements())

{

NetworkInterface

ni

=

netInterfaces.nextElement()

System.out.println("DisplayName:"

+

ni.getDisplayName())

System.out.println("Name:"

+

ni.getName())

Enumeration<InetAddress>

ips

=

ni.getInetAddresses()

while

(ips.hasMoreElements())

{

System.out.println("IP:"

+

ips.nextElement().getHostAddress())

ipTemp=

ni.getInetAddresses().nextElement().getHostAddress()

if(ipTemp!="127.0.0.1"

&&

!"127.0.0.1".equals(ipTemp))

{

ip=ipTemp

}

}

}

}catch(Exception

ee)

{

ee.printStackTrace()

}

第二种:也是本机的:

InetAddress

addr

=

InetAddress.getLocalHost()

ip=addr.getHostAddress().toString()//获得本机IP

方法如下:

方法一,使用CMD命令:

public static String getLocalIPForCMD(){

StringBuilder sb = new StringBuilder()

String command = "cmd.exe /c ipconfig | findstr IPv4"

try {

Process p = Runtime.getRuntime().exec(command)

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))

String line = null

while((line = br.readLine()) != null){

line = line.substring(line.lastIndexOf(":")+2,line.length())

sb.append(line)

}

br.close()

p.destroy()

} catch (IOException e) {

e.printStackTrace()

}

return sb.toString()

}

方法二,使用Java方法

public static String getLocalIPForJava(){

StringBuilder sb = new StringBuilder()

try {

Enumeration<NetworkInterface>en = NetworkInterface.getNetworkInterfaces()

while (en.hasMoreElements()) {

NetworkInterface intf = (NetworkInterface) en.nextElement()

Enumeration<InetAddress>enumIpAddr = intf.getInetAddresses()

while (enumIpAddr.hasMoreElements()) {

InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement()

if (!inetAddress.isLoopbackAddress() &&!inetAddress.isLinkLocalAddress()

&&inetAddress.isSiteLocalAddress()) {

sb.append(inetAddress.getHostAddress().toString()+"\n")

}

}

}

} catch (SocketException e) { }

return sb.toString()

}

public void PingAll() throws Exception{

//首先得到本机的IP,得到网段

InetAddress host = InetAddress.getLocalHost()

String hostAddress = host.getHostAddress()

int k=0

k=hostAddress.lastIndexOf(".")

String ss = hostAddress.substring(0,k+1)

for(int i=1i <=255i++){ //对所有局域网Ip

String iip=ss+i

Ping(iip)

}