歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 獲取本機IP

Java 獲取本機IP

日期:2017/3/1 9:18:27   编辑:Linux編程

Java 獲取本機IP,Linux上也適用。

import java.io.*;
import java.util.*;
import java.net.*;

public class GetIP {
public static void main (String[] args) throws Exception {
/*
String s = InetAddress.getLocalHost().toString();
System.out.println(s);

String[] arr = s.split("/");
System.out.println("host name:\n" + arr[0]);
System.out.println("localhost IP:\n" + arr[1]);

*/
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress i = (InetAddress) ee.nextElement();
System.out.println(i.getHostAddress());
}
}

}


}

Copyright © Linux教程網 All Rights Reserved