21xrx.com
2024-09-19 10:01:22 Thursday
登录
文章检索 我的文章 写文章
如何用Java获取当前IP地址和当天日期?
2023-06-13 13:00:38 深夜i     --     --
Java IP地址 日期

在开发Java应用程序的过程中,获取当前IP地址和当天日期是常见的需求。本文将介绍两种Java获取当前IP地址的方法,以及获取当天日期的方法。

获取当前IP地址

方法一:使用Java标准库

Java标准库提供了InetAddress类,可以获取本机的IP地址。以下是示例代码:


import java.net.InetAddress;

import java.net.UnknownHostException;

public class GetIPAddress {

  public static void main(String[] args) {

    try {

      InetAddress ip = InetAddress.getLocalHost();

      System.out.println("Current IP address : " + ip.getHostAddress());

    } catch (UnknownHostException e) {

      e.printStackTrace();

    }

  }

}

方法二:使用第三方库

如果需要获取公网IP地址,可以使用第三方库。例如,使用Apache Commons Net库,可以使用以下代码:


import java.io.IOException;

import org.apache.commons.net.util.SubnetUtils;

public class GetIPAddress {

  public static void main(String[] args) {

    try {

      String ipAddress = new SubnetUtils("0.0.0.0/0").getInfo().getAddress();

      System.out.println("Current IP address : " + ipAddress);

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

获取当天日期

在Java中,获取当天日期可以使用java.util.Date类和java.time.LocalDate类。

方法一:使用java.util.Date类


import java.util.Date;

public class GetCurrentDate {

  public static void main(String[] args) {

    Date currentDate = new Date();

    System.out.println("Current date is : " + currentDate);

  }

}

方法二:使用java.time.LocalDate类


import java.time.LocalDate;

public class GetCurrentDate {

  public static void main(String[] args) {

    LocalDate currentDate = LocalDate.now();

    System.out.println("Current date is : " + currentDate);

  }

}

以上就是获取当前IP地址和当天日期的两种方法,可以根据实际情况选择合适的方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复