一、Java獲取本機IP
在Java中獲取本機IP地址是比較簡單的,可以通過InetAddress
類來實現。下面是獲取本機IP的示例代碼:
import java.net.InetAddress;
public class GetLocalIP {
public static void main(String[] args) {
try{
InetAddress address = InetAddress.getLocalHost();
System.out.println("本機IP地址:" + address.getHostAddress());
}catch(Exception e){
e.printStackTrace();
}
}
}
運行上述代碼後,可以得到本機IP地址。
二、Java獲取指定主機的IP
除了可以獲取本機IP地址外,Java還可以獲取指定主機的IP地址。下面是獲取指定主機IP的示例代碼:
import java.net.InetAddress;
public class GetSpecifiedIP {
public static void main(String[] args) {
try{
InetAddress address = InetAddress.getByName("www.baidu.com");
System.out.println("百度IP地址:" + address.getHostAddress());
}catch(Exception e){
e.printStackTrace();
}
}
}
運行上述代碼後,可以得到輸入的主機IP地址。
三、Java獲取本機所有IP地址
有時候我們需要獲取本機的所有IP地址。Java中也可以通過InetAddress
類來實現。下面是獲取本機所有IP地址的示例代碼:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class GetAllIP {
public static void main(String[] args) {
try{
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof InetAddress && !ip.isLoopbackAddress()) {
System.out.println(netInterface.getName() + " " + ip.getHostAddress());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
運行上述代碼後,可以得到本機所有IP地址。
四、Java獲取MAC地址
在Java中獲取MAC地址需要藉助第三方庫。下面是獲取MAC地址的示例代碼:
import java.net.InetAddress;
import java.net.NetworkInterface;
public class GetMacAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append(":");
}
// 位元組轉換為整數
int temp = mac[i] & 0xff;
String str = Integer.toHexString(temp);
if (str.length() == 1) {
sb.append("0" + str);
} else {
sb.append(str);
}
}
System.out.println("MAC地址:" + sb.toString().toUpperCase());
} catch (Exception e) {
e.printStackTrace();
}
}
}
運行上述代碼後,可以得到本機的MAC地址。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/150571.html