您的位置:首页 > 编程语言 > Java开发

java获取本机ip和mac地址

2016-01-20 14:57 806 查看
工作中用到的  总结下,与大家分享

package com.taile.msc.util;

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.net.UnknownHostException;

/*

 * 作者:。。。。

 */

public class IpAndMacUtil {

 /**

  *

  * @param args

  *

  * @throws UnknownHostException

  *

  * @throws SocketException

  *

  */

 public static String getLocalMac() throws SocketException, UnknownHostException {

  InetAddress ia = InetAddress.getLocalHost();

  byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();

  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);

   if (str.length() == 1) {

    sb.append("0" + str.toUpperCase());

   } else {

    sb.append(str.toUpperCase());

   }

  }

  return sb.toString();

 }

 public static String getLocalIp() throws UnknownHostException {

  return InetAddress.getLocalHost().getHostAddress();

 }

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: