ZBLOG

golang 获取指定网卡的mac地址和IP地址

可以使用net包中的接口函数来获取指定网卡的mac地址和IP地址。

获取mac地址:

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. func main() {
  7. ifaces, err := net.Interfaces()
  8. if err != nil {
  9. fmt.Println(err)
  10. return
  11. }
  12. for _, iface := range ifaces {
  13. if iface.Name == "eth0" {
  14. fmt.Println("MAC address: ", iface.HardwareAddr)
  15. }
  16. }
  17. }

其中,net.Interfaces()函数返回当前系统上所有网络接口的信息列表。通过遍历这个列表,找到名称为“eth0”的网络接口,就可以获取它的MAC地址了。

获取IP地址:

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. func main() {
  7. ifaces, err := net.Interfaces()
  8. if err != nil {
  9. fmt.Println(err)
  10. return
  11. }
  12. for _, iface := range ifaces {
  13. if iface.Name == "eth0" {
  14. addrs, err := iface.Addrs()
  15. if err != nil {
  16. fmt.Println(err)
  17. continue
  18. }
  19. for _, addr := range addrs {
  20. ipnet, ok := addr.(*net.IPNet)
  21. if ok && !ipnet.IP.IsLoopback() {
  22. if ipnet.IP.To4() != nil {
  23. fmt.Println("IPv4 address: ", ipnet.IP.String())
  24. } else {
  25. fmt.Println("IPv6 address: ", ipnet.IP.String())
  26. }
  27. }
  28. }
  29. }
  30. }
  31. }

类似地,首先遍历网络接口信息列表,找到目标接口“eth0”,然后调用iface.Addrs()方法获取该接口上的所有IP地址。遍历这些IP地址,判断是IPv4还是IPv6,并输出对应的地址即可。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=265

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?