[英]How to get our own Wireless LAN Ip address using java
Following code is giving Ethernet Address but I need to get Wirless LAN address以下代码提供以太网地址,但我需要获得无线局域网地址
InetAddress inet;
try {
inet = InetAddress.getLocalHost();
myIp.setText(inet.getHostAddress());
} catch (UnknownHostException ex) {
Logger.getLogger(frontPageController.class.getName()).log(Level.SEVERE, null, ex);
}
But what is the code to get wireless LAN ip address ??但是获取无线局域网IP地址的代码是什么??
This is an example how you can explore your network interfaces with java.net.NetworkInterface
:这是一个如何使用
java.net.NetworkInterface
探索网络接口的示例:
@Test
public void test() throws Exception {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
// drop inactive
if (!networkInterface.isUp())
continue;
// smth we can explore
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
System.out.println(String.format("NetInterface: name [%s], ip [%s]",
networkInterface.getDisplayName(), addr.getHostAddress()));
}
}
}
Below code is for identifying IP of ethernet or wifi based on the type -下面的代码用于根据类型识别以太网或 wifi 的 IP -
//useIPv4=true if you want to get ipv4 address
//type="eth0" if you want to get ethernet interface (eth0) IP : change with correct interface name
//type="wlan0" if you want to use wifi interface (wlan0) : change with correct interface name
public static String getIPAddress(boolean useIPv4, String type) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
boolean isIPv4 = sAddr.indexOf(':')<0;
if(intf.getDisplayName().equalsIgnoreCase(type)) { //checking here the interface type of your choice
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
return delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
}
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "ERROR";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.