public class Test6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InetAddress ia=null
try {
ia=ia.getLocalHost()
String localname=ia.getHostName()
String localip=ia.getHostAddress()
System.out.println("本机名称是:"+ localname)
System.out.println("本机的ip是 :"+localip)
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
方法如下:方法一,使用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()
}