本文介绍了如何获取以太网IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经很难获得确切的以太网ip地址.

I''ve tired to get exact ethernet ip address.

InetAddress ip=InetAddress.getLocalHost();
String iaddr = ip.getHostAddress();



它仅返回本地主机地址.我只需要以太网地址..

请帮帮我..



It return localhost address only. I need ethernet address only..

pls help me..

推荐答案

public static void main(String[] args) {

		try {
		    InetAddress addr = InetAddress.getLocalHost();

		    // Get IP Address
		    byte[] ipAddr = addr.getAddress();

		    // Get hostname
		    String hostname = addr.getHostName();
		    System.out.println("hostname " + hostname);
		    System.out.println("IP Address " + convertIP(ipAddr));
		} catch (java.net.UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Convert to dot representation
	private static String convertIP(byte[] ipAddr){
	    String ipAddrStr = "";
	    for (int i=0; i<ipAddr.length; i++) {
	        if (i > 0) {
	            ipAddrStr += ".";
	        }
	        ipAddrStr += ipAddr[i]&0xFF;
	    }
	    return ipAddrStr;
	}


报价:

以下代码在Linux(ubuntu)上运行.您必须在Windows上使用,只需将"ppp0"更改为"ppp2".肯定会返回互联网IP地址.

The following code working on Linux(ubuntu).. If u have to use on windows, just change the "ppp0" to "ppp2". surely it will return the internet IP Address.


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import javax.swing.JOptionPane;

public class ShowIp {

    public static void main(String[] args) throws SocketException {
        NetworkInterface ni = NetworkInterface.getByName("ppp0");
        Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();


        while (inetAddresses.hasMoreElements()) {
            InetAddress ia = inetAddresses.nextElement();
            if (!ia.isLinkLocalAddress()) {
                JOptionPane.showMessageDialog(null, ia.getHostAddress());
            }
        }
    }
}


这篇关于如何获取以太网IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:09