java怎么获取本机的ip地址_java如何获取本机IP

java如何获取本机IP

1 import java.net.*;

2

3 public class Test6 {

4

5 public static void main(String[] args) {

6 // TODO Auto-generated method stub

7 InetAddress ia=null;

8 try {

9 ia=ia.getLocalHost();

10

11 String localname=ia.getHostName();

12 String localip=ia.getHostAddress();

13 System.out.println("本机名称是:"+ localname);

14 System.out.println("本机的ip是 :"+localip);

15 } catch (Exception e) {

16 // TODO Auto-generated catch block

17 e.printStackTrace();

18 }

19 }

20

21 }

获取所有IPv4的IP地址:

1 public static List getLocalIPList() {

2 List ipList = new ArrayList();

3 try {

4 Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();

5 NetworkInterface networkInterface;

6 Enumeration inetAddresses;

7 InetAddress inetAddress;

8 String ip;

9 while (networkInterfaces.hasMoreElements()) {

10 networkInterface = networkInterfaces.nextElement();

11 inetAddresses = networkInterface.getInetAddresses();

12 while (inetAddresses.hasMoreElements()) {

13 inetAddress = inetAddresses.nextElement();

14 if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4

15 ip = inetAddress.getHostAddress();

16 ipList.add(ip);

17 }

18 }

19 }

20 } catch (SocketException e) {

21 e.printStackTrace();

22 }

23 return ipList;

24 }

标签:java,String,inetAddresses,IP,ip,ia,inetAddress,本机

来源: https://www.cnblogs.com/java-dyb/p/10912808.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值