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;
        }
  • 相关阅读:
    高斯消元法
    DP:Making the Grade(POJ 3666)
    Heap:Sunscreen(POJ 3614)
    ShortestPath:Silver Cow Party(POJ 3268)
    ShortestPath:Wormholes(POJ 3259)
    ShortestPath:Six Degrees of Cowvin Bacon(POJ 2139)
    DP:Bridging Signals(POJ 1631)
    DP:Wooden Sticks(POJ 1065)
    Greedy:Protecting the Flowers(POJ 3262)
    Greedy:Stripes(POJ 1826)
  • 原文地址:https://www.cnblogs.com/stono/p/5664083.html
Copyright © 2011-2022 走看看