JAVAはネイティブIP(イントラネットIPとパブリックネットIPを含む)を取得する
2096 ワード
Springクライアント要求IPを取得します.詳細は以下を参照してください.https://blog.csdn.net/NRlovestudy/article/details/90900925
本論文では,プロジェクトが存在するシステムのIP(ローカルIP)を取得する.
ローカルIPは、ローカルエリアネットワークIPとパブリックネットワークIPの2つに分けられます.以下に、具体的なコード実装(WindowsとLinuxともに適用)を示します.
1、LAN IPの取得
2、パブリックネットワークIPの取得
参照先:https://www.cnblogs.com/webnote/p/5757435.html
Java curlコマンドの実行
呼び出しコード:
本論文では,プロジェクトが存在するシステムのIP(ローカルIP)を取得する.
ローカルIPは、ローカルエリアネットワークIPとパブリックネットワークIPの2つに分けられます.以下に、具体的なコード実装(WindowsとLinuxともに適用)を示します.
1、LAN IPの取得
// IP
// Linux , curl
public static String getIpAddress() {
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println("IP " + e.toString());
}
return "";
}
2、パブリックネットワークIPの取得
参照先:https://www.cnblogs.com/webnote/p/5757435.html
Java curlコマンドの実行
// curl
// curl icanhazip.com , IP
public static String execCurl(String[] cmds) {
ProcessBuilder process = new ProcessBuilder(cmds);
Process p;
try {
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
return builder.toString();
} catch (IOException e) {
System.out.print("error");
e.printStackTrace();
}
return null;
}
呼び出しコード:
String[] cmds={"curl","icanhazip.com"};// ,
String localIP = IPUtil.execCurl(cmds).trim();