java 网卡物理地址_【java】获取本机IP地址和网卡的MAC地址

本文介绍了如何使用Java获取本机IP地址和网卡的MAC地址。通过示例代码展示了具体实现方法,包括`getIpAddress()`和`getMacAddress()`两个函数,帮助开发者在需要网络硬件标识时进行操作。
摘要由CSDN通过智能技术生成

平凡也就两个字: 懒和惰;

成功也就两个字: 苦和勤;

优秀也就两个字: 你和我。

跟着我从0学习JAVA、spring全家桶和linux运维等知识,带你从懵懂少年走向人生巅峰,迎娶白富美!

关注微信公众号【 IT特靠谱】,每天都会分享技术心得~

获取本机IP地址和网卡的MAC地址

1 什么是MAC地址?

MAC地址(英语:Media Access Control Address),直译为媒体存取控制位址,也称为局域网地址(LAN Address),MAC位址,以太网地址(Ethernet Address)或物理地址(Physical Address),它是一个用来确认网络设备位置的位址。在OSI模型中,第三层网络层负责IP地址,第二层数据链路层则负责MAC位址  。MAC地址用于在网络中唯一标示一个网卡,一台设备若有一个或多个网卡,则每个网卡都有一个唯一的MAC地址!

2 获取IP地址和MAC地址

下面通过java来获取本地ip地址和网卡MAC地址。

2.1 获取IP地址

/**

* 获取本机IP地址

*/

private static String getIpAddress() throws UnknownHostException {

InetAddress ia = InetAddress.getLocalHost();

return ia.getHostAddress();

}

2.2 获取网卡的MAC地址

/**

* 获取本机使用网卡的MAC地址

*/

private static String getMacAddress() throws UnknownHostException, SocketException {

//获取IP地址,输出示例:WCGZ-DZ-013803/10.88.12.117

InetAddress ia = InetAddress.getLocalHost();

//获取网卡的MAC地址

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

} else {

sb.append(str);

}

}

return sb.toString().toUpperCase();

}

3 完整代码

import java.net.InetAddress;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.net.UnknownHostException;

import lombok.extern.slf4j.Slf4j;

@Slf4j

public class Main {

public static void main(String[] args) throws UnknownHostException, SocketException {

//获取本机IP地址

String ip = getIpAddress();

//获取本机网卡的MAC地址

String mac = getMacAddress();

log.info("IP地址为:{}, 本机网卡MAC地址为:{}", ip, mac);

}

/**

* 获取本机IP地址

*/

private static String getIpAddress() throws UnknownHostException {

InetAddress ia = InetAddress.getLocalHost();

return ia.getHostAddress();

}

/**

* 获取本机使用网卡的MAC地址

*/

private static String getMacAddress() throws UnknownHostException, SocketException {

//获取IP地址,输出示例:WCGZ-DZ-013803/10.88.12.117

InetAddress ia = InetAddress.getLocalHost();

//获取网卡的MAC地址

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

} else {

sb.append(str);

}

}

return sb.toString().toUpperCase();

}

}

4 测试结果

8edaae8fddcd14fc8fe405024c1441c0.png

如果对你有帮助或需要技术支持,关注一下本人吧~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值