Due to work needs this week, we need to obtain the export IP corresponding to the server. Here is a record of how to obtain it.
How do I obtain the egress IP address of a vm in Linux
In this case, the machine can access the external network, otherwise obtaining the exit IP is not meaningful.
Methods a
curl cip.cc
Copy the code
IP: 111. XXX. XXX. Address: 89 Beijing operators: China unicom data 2: | Beijing unicom data 3: China | Beijing Beijing unicom URL: http://www.cip.cc/111.xxx.xxx.89Copy the code
The information obtained in this request mode is very detailed, including the egress IP address, carrier, and address
If you just get the IP, you can use it (but there will be a lag when you try)
curl ip.cip.cc
Copy the code
You can check it out at cip. Cc
Way 2
curl ifconfig.io
Copy the code
The request returns the exit IP directly
111.xxx.xxx.89
Copy the code
You can log in to ifconfig. IO to view some common curl commands
Methods three
With services like AWS
curl http://checkip.amazonaws.com
Copy the code
The request also returns the exit IP directly
111.xxx.xxx.89
Copy the code
Java code
@Slf4j
public class IpUtils {
public static final String AWS_COM_URL = "http://checkip.amazonaws.com";
// This method is not recommended because it is likely to lag
public static final String CIP_CC_URL = "http://ip.cip.cc";
public static final String IFCONFIG_IO_URL = "http://ifconfig.io/ip";
/** * Directly obtain the IP address of the host */
public static void getLocalIp(a) {
try {
InetAddress localHost = InetAddress.getLocalHost();
String localIp = localHost.getHostAddress();
log.info("localIp:{}", localIp);
} catch (Exception e) {
log.error("getLocalIp error, msg:{}", e.getMessage(), e); }}/** * Obtain the local egress Ip * by accessing some external services@throws MalformedURLException
*/
public static void getExternalIp(String urlStr) throws MalformedURLException {
if (StringUtils.isEmpty(urlStr)) {
urlStr = AWS_COM_URL;
}
URL url = new URL(urlStr);
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()))) {
String ip = bufferedReader.readLine();
log.info("externalIp:{}", ip);
} catch (IOException e) {
log.error("get ExternalIp error, msg:{}", e.getMessage(), e); }}public static void main(String[] args) throws MalformedURLException { IpUtils.getLocalIp(); IpUtils.getExternalIp(IpUtils.AWS_COM_URL); IpUtils.getExternalIp(IpUtils.CIP_CC_URL); IpUtils.getExternalIp(IpUtils.IFCONFIG_IO_URL); }}Copy the code