| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package midware.util.helper;
- import java.net.Inet4Address;
- import java.net.InetAddress;
- import java.net.NetworkInterface;
- import java.net.SocketException;
- import java.util.Enumeration;
- public class IpHelper {
- public static String getIp4(){
- String hostIP="";
- try {
- Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
- while (networkInterfaces.hasMoreElements()) {
- NetworkInterface ni = networkInterfaces.nextElement();
- Enumeration<InetAddress> nias = ni.getInetAddresses();
- while (nias.hasMoreElements()) {
- InetAddress ia = nias.nextElement();
- if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
- hostIP=ia.getHostAddress();
- }
- }
- }
- } catch (SocketException e) {
- e.printStackTrace();
- }
- return hostIP;
- }
- public static String getMac() {
- String mac = "";
- try {
- Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
- while (networkInterfaces.hasMoreElements()) {
- NetworkInterface ni = networkInterfaces.nextElement();
- if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()) continue;
- boolean ip4 = false;
- Enumeration<InetAddress> nias = ni.getInetAddresses();
- while (nias.hasMoreElements()) {
- InetAddress ia = nias.nextElement();
- if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
- ip4 = true;
- }
- }
- if (!ip4) continue;
- byte[] macByte = ni.getHardwareAddress();
- if (macByte == null) continue;
- StringBuilder buf = new StringBuilder();
- for (byte aMac : macByte) {
- buf.append(String.format("%02X-", aMac));
- }
- if (buf.length() > 0) {
- buf.deleteCharAt(buf.length() - 1);
- mac = buf.toString();
- break;
- }
- }
- } catch (SocketException e) {
- e.printStackTrace();
- }
- return mac;
- }
- }
|