IPUtil.java
1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package io.mycat.util;
import java.net.*;
import java.util.Enumeration;
/**
* Created by xueyin on 2018/11/29.
*/
public class IPUtil {
/**
* 注意本方法不支持多网卡时获取IP地址
*/
public static String fetchLocalIP() {
String localIP = "127.0.0.1";
DatagramSocket sock = null;
try {
SocketAddress socket_addr = new InetSocketAddress(InetAddress.getByName("1.2.3.4"), 1);
sock = new DatagramSocket();
sock.connect(socket_addr);
localIP = sock.getLocalAddress().getHostAddress();
} catch (Exception e) {
e.printStackTrace();
} finally {
sock.disconnect();
sock.close();
sock = null;
}
return localIP;
}
public static String fetchIpByHost(String host) {
try {
InetAddress address = InetAddress.getByName(host);
return address.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
// String ip = IPUtil.fetchIpByHost("www.baidu.com");
String ip = IPUtil.fetchLocalIP();
System.out.println(ip);
}
}