zoukankan      html  css  js  c++  java
  • java如何获取本机IP

    java如何获取本机IP

    import java.net.*;
    
    public class Test6 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            InetAddress ia=null;
            try {
                ia=ia.getLocalHost();
                
                String localname=ia.getHostName();
                String localip=ia.getHostAddress();
                System.out.println("本机名称是:"+ localname);
                System.out.println("本机的ip是 :"+localip);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }

    获取所有IPv4的IP地址:

    public static List<String> getLocalIPList() {
            List<String> ipList = new ArrayList<String>();
            try {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                NetworkInterface networkInterface;
                Enumeration<InetAddress> inetAddresses;
                InetAddress inetAddress;
                String ip;
                while (networkInterfaces.hasMoreElements()) {
                    networkInterface = networkInterfaces.nextElement();
                    inetAddresses = networkInterface.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        inetAddress = inetAddresses.nextElement();
                        if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                            ip = inetAddress.getHostAddress();
                            ipList.add(ip);
                        }
                    }
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
            return ipList;
        }
  • 相关阅读:
    url-pattern / /*匹配
    velocity入门
    配置eclipse插件
    Myeclipse 2014 破解
    Eclipse kepler 安装 Dynamic Web Project差距WTP
    Errors running builder 'Faceted Project Validation Builder' on project
    JSF web.xml的各类参数属性配置
    bpm 学习笔记一
    love is ... ...
    .sh_history文件的管理机制
  • 原文地址:https://www.cnblogs.com/stono/p/5664083.html
Copyright © 2011-2022 走看看