NetUtils.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright © 2018 Zhenjie Yan.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.qingdaofushan.homecaresas.component;
  17. import java.net.InetAddress;
  18. import java.net.NetworkInterface;
  19. import java.net.SocketException;
  20. import java.util.Enumeration;
  21. import java.util.regex.Pattern;
  22. /**
  23. * Created by Zhenjie Yan on 2018/6/9.
  24. */
  25. public class NetUtils {
  26. /**
  27. * Ipv4 address check.
  28. */
  29. private static final Pattern IPV4_PATTERN = Pattern.compile(
  30. "^(" + "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" +
  31. "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
  32. /**
  33. * Check if valid IPV4 address.
  34. *
  35. * @param input the address string to check for validity.
  36. *
  37. * @return True if the input parameter is a valid IPv4 address.
  38. */
  39. public static boolean isIPv4Address(String input) {
  40. return IPV4_PATTERN.matcher(input).matches();
  41. }
  42. /**
  43. * Get local Ip address.
  44. */
  45. public static InetAddress getLocalIPAddress() {
  46. Enumeration<NetworkInterface> enumeration = null;
  47. try {
  48. enumeration = NetworkInterface.getNetworkInterfaces();
  49. } catch (SocketException e) {
  50. e.printStackTrace();
  51. }
  52. if (enumeration != null) {
  53. while (enumeration.hasMoreElements()) {
  54. NetworkInterface nif = enumeration.nextElement();
  55. Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
  56. if (inetAddresses != null) {
  57. while (inetAddresses.hasMoreElements()) {
  58. InetAddress inetAddress = inetAddresses.nextElement();
  59. if (!inetAddress.isLoopbackAddress() && isIPv4Address(inetAddress.getHostAddress())) {
  60. return inetAddress;
  61. }
  62. }
  63. }
  64. }
  65. }
  66. return null;
  67. }
  68. }