java获取本地机器IP地址和访问的端口

        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
	while (allNetInterfaces.hasMoreElements()){
		NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
		Enumeration addresses = netInterface.getInetAddresses();
		while (addresses.hasMoreElements()){
			InetAddress ip = (InetAddress) addresses.nextElement();
			if (ip != null && ip instanceof Inet4Address
                    		&& !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                    		&& ip.getHostAddress().indexOf(":")==-1){
				System.out.println("本机的IP = " + ip.getHostAddress());
						
					} 
				}
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String port = objectNames.iterator().next().getKeyProperty("port");//获取访问的端口

 

你可能感兴趣的:(java获取本地机器IP地址和访问的端口)