/util/src/main/java/com/webank/wedatasphere/qualitis/net/LocalNetwork.java

https://github.com/WeBankFinTech/Qualitis · Java · 80 lines · 53 code · 8 blank · 19 comment · 11 complexity · 6aa0b075505a43d43dc9c49cec3c783c MD5 · raw file

  1. /*
  2. * Copyright 2019 WeBank
  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.webank.wedatasphere.qualitis.net;
  17. import java.io.BufferedReader;
  18. import java.io.IOException;
  19. import java.io.InputStreamReader;
  20. import java.net.*;
  21. import java.util.ArrayList;
  22. import java.util.Enumeration;
  23. import java.util.List;
  24. /**
  25. * @author howeye
  26. */
  27. public class LocalNetwork {
  28. private static final String WINDOWS_PREFIX = "win";
  29. private LocalNetwork() {
  30. // Default Contructor
  31. }
  32. public static String getLocalIpByFirstNetCard() {
  33. String os = System.getProperty("os.name").toLowerCase();
  34. if (os.startsWith(WINDOWS_PREFIX)) {
  35. try {
  36. for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) {
  37. NetworkInterface item = e.nextElement();
  38. for (InterfaceAddress address : item.getInterfaceAddresses()) {
  39. if (item.isLoopback() || !item.isUp()) {
  40. continue;
  41. }
  42. if (address.getAddress() instanceof Inet4Address) {
  43. Inet4Address inet4Address = (Inet4Address) address.getAddress();
  44. return inet4Address.getHostAddress();
  45. }
  46. }
  47. }
  48. return InetAddress.getLocalHost().getHostAddress();
  49. } catch (SocketException | UnknownHostException e) {
  50. throw new RuntimeException(e);
  51. }
  52. } else {
  53. Process process = null;
  54. List<String> processList = new ArrayList<String>();
  55. try {
  56. process = Runtime.getRuntime().exec("hostname -i");
  57. BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
  58. String line = "";
  59. while ((line = input.readLine()) != null) {
  60. processList.add(line);
  61. }
  62. input.close();
  63. } catch (IOException e) {
  64. e.printStackTrace();
  65. }
  66. if (processList.size() == 1) {
  67. return processList.get(0);
  68. }
  69. return null;
  70. }
  71. }
  72. }