Java获取本机的ip地址和Mac地址

Java获取本机的ip地址

  //得到IP,
    	InetAddress ia = InetAddress.getLocalHost();
    	String ip=ia.toString().split("/")[1];
    	System.out.println(ia);
    	System.out.println("本机的IP:"+ip);
    	@SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
        
    	//得到IP,输出PC-201309011313/122.206.73.83
    	InetAddress ia2 = InetAddress.getLocalHost();
    	

获取本机的mac地址,注意如果要是需要在另一个class文件引用其输出,一定要注意命名的重合(孩子困扰了好久,才发现名字重了)

public static String getLocalMac(InetAddress ia) throws SocketException {
         //获取网卡,获取地址
         byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
         //System.out.println("mac数组长度:"+mac.length);
         StringBuffer sb = new StringBuffer("");
         for(int i=0; i<mac.length; i++) {
        	 if(i!=0) {
        		 sb.append("-");
        	 }
        	 //字节转换为整数
        	 int temp = mac[i]&0xff;
        	 String str = Integer.toHexString(temp);
        	 //System.out.println("每8位:"+str);
        	 if(str.length()==1) {
        		 sb.append("0"+str);
        		 }else {
        			 sb.append(str);
        		 }

完整代码

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class trymyself1 {


	public static String getLocalMac(InetAddress ia) throws SocketException {
         //获取网卡,获取地址
         byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
         //System.out.println("mac数组长度:"+mac.length);
         StringBuffer sb = new StringBuffer("");
         for(int i=0; i<mac.length; i++) {
        	 if(i!=0) {
        		 sb.append("-");
        	 }
        	 //字节转换为整数
        	 int temp = mac[i]&0xff;
        	 String str = Integer.toHexString(temp);
        	 //System.out.println("每8位:"+str);
        	 if(str.length()==1) {
        		 sb.append("0"+str);
        		 }else {
        			 sb.append(str);
        		 }
         }
         
         String myMac=sb.toString().toUpperCase();
         //System.out.println("本机MAC地址:"+myMac);
       
         return myMac;
         
}
      
public static void main(String[] args) throws UnknownHostException {

	//得到IP,输出PC-201309011313/122.206.73.83
	InetAddress ia = InetAddress.getLocalHost();
	String ip=ia.toString().split("/")[1];
	
	System.out.println(ia);
	System.out.println("IP:"+ip);
	
	try {
		getLocalMac(ia);
	} catch (SocketException e) {
		e.printStackTrace();}
}

}

你可能感兴趣的:(Java,java,tcp/ip)