基础版中间件

IpHelper.java 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package midware.util.helper;
  2. import java.net.Inet4Address;
  3. import java.net.InetAddress;
  4. import java.net.NetworkInterface;
  5. import java.net.SocketException;
  6. import java.util.Enumeration;
  7. public class IpHelper {
  8. public static String getIp4(){
  9. String hostIP="";
  10. try {
  11. Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
  12. while (networkInterfaces.hasMoreElements()) {
  13. NetworkInterface ni = networkInterfaces.nextElement();
  14. Enumeration<InetAddress> nias = ni.getInetAddresses();
  15. while (nias.hasMoreElements()) {
  16. InetAddress ia = nias.nextElement();
  17. if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
  18. hostIP=ia.getHostAddress();
  19. }
  20. }
  21. }
  22. } catch (SocketException e) {
  23. e.printStackTrace();
  24. }
  25. return hostIP;
  26. }
  27. public static String getMac() {
  28. String mac = "";
  29. try {
  30. Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
  31. while (networkInterfaces.hasMoreElements()) {
  32. NetworkInterface ni = networkInterfaces.nextElement();
  33. if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()) continue;
  34. boolean ip4 = false;
  35. Enumeration<InetAddress> nias = ni.getInetAddresses();
  36. while (nias.hasMoreElements()) {
  37. InetAddress ia = nias.nextElement();
  38. if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
  39. ip4 = true;
  40. }
  41. }
  42. if (!ip4) continue;
  43. byte[] macByte = ni.getHardwareAddress();
  44. if (macByte == null) continue;
  45. StringBuilder buf = new StringBuilder();
  46. for (byte aMac : macByte) {
  47. buf.append(String.format("%02X-", aMac));
  48. }
  49. if (buf.length() > 0) {
  50. buf.deleteCharAt(buf.length() - 1);
  51. mac = buf.toString();
  52. break;
  53. }
  54. }
  55. } catch (SocketException e) {
  56. e.printStackTrace();
  57. }
  58. return mac;
  59. }
  60. }