獲取本機IP地址

 獲取本機IP地址。
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			StringBuilder IFCONFIG = new StringBuilder();
			try {
				for (Enumeration<NetworkInterface> en = NetworkInterface
						.getNetworkInterfaces(); en.hasMoreElements();) {
					NetworkInterface intf = en.nextElement();
					for (Enumeration<InetAddress> enumIpAddr = intf
							.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()
								&& !inetAddress.isLinkLocalAddress()
								&& inetAddress.isSiteLocalAddress()) {
							IFCONFIG.append(inetAddress.getHostAddress()
									.toString()
									+ "\n");
						}
					}
				}
			} catch (Exception ex) {
			}
			System.out.println(IFCONFIG);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章