java代碼求ip和mac地址,請問什麼是 IP 地址?什麼是 MAC 地址?

本文目錄一覽:

java如何獲取mac地址?

以windows舉例。

運行命令” cmd ipconfig /all”就會出現以下結果

Physical Address. . . . . . . . . : 20-CF-30-9A-60-EE

java就能過這樣的命令來獲取。以下是示例。

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class TestMac

{

public static void main(String[] args) {

System.out.println(“Operation System=” + getOsName());

System.out.println(“Mac Address=” + getMACAddress());

System.out.println(“通過ip獲取mac”+getMACAddress(“192.168.1.101”));

}

public static String getOsName() {

String os = “”;

os = System.getProperty(“os.name”);

return os;

}

public static String getMACAddress() {

String address = “”;

String os = getOsName();

if (os.startsWith(“Windows”)) {

try {

String command = “cmd.exe /c ipconfig /all”;

Process p = Runtime.getRuntime().exec(command);

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;

while ((line = br.readLine()) != null) {

if (line.indexOf(“Physical Address”) 0) {

int index = line.indexOf(“:”);

index += 2;

address = line.substring(index);

break;

}

}

br.close();

return address.trim();

} catch (IOException e) {

}

} else if (os.startsWith(“Linux”)) {

String command = “/bin/sh -c ifconfig -a”;

Process p;

try {

p = Runtime.getRuntime().exec(command);

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;

while ((line = br.readLine()) != null) {

if (line.indexOf(“HWaddr”) 0) {

int index = line.indexOf(“HWaddr”) + “HWaddr”.length();

address = line.substring(index);

break;

}

}

br.close();

} catch (IOException e) {

}

}

address = address.trim();

return address;

}

public static String getMACAddress(String ipAddress) {

String str = “”, strMAC = “”, macAddress = “”;

try {

Process pp = Runtime.getRuntime().exec(“nbtstat -a ” + ipAddress);

InputStreamReader ir = new InputStreamReader(pp.getInputStream());

LineNumberReader input = new LineNumberReader(ir);

for (int i = 1; i 100; i++) {

str = input.readLine();

if (str != null) {

if (str.indexOf(“MAC Address”) 1) {

strMAC = str.substring(str.indexOf(“MAC Address”) + 14,

str.length());

break;

}

}

}

} catch (IOException ex) {

return “Can’t Get MAC Address!”;

}

//

if (strMAC.length() 17) {

return “Error!”;

}

macAddress = strMAC.substring(0, 2) + “:” + strMAC.substring(3, 5)

+ “:” + strMAC.substring(6, 8) + “:” + strMAC.substring(9, 11)

+ “:” + strMAC.substring(12, 14) + “:”

+ strMAC.substring(15, 17);

//

return macAddress;

}

}

劍天夢的回答原理和我這個一樣,都是通過Process 執行命令。 我直接補充到答案里了。不過

我這邊運行那個命令出來的結果很多,那麼花的時間就長了。優點是能夠獲取別人的mac地址 。

JAVA如何獲取區域網內所有安卓設備的ip地址,MAC以及序列號?

1.得到區域網網段,可由自己機器的IP來確定 (也可以手動獲取主機IP-CMD-ipconfig /all)

2.根據IP類型,一次遍歷區域網內IP地址

JAVA類,編譯之後直接運行便可以得到區域網內所有IP,具體怎樣使用你自己編寫相應代碼調用便可

代碼如下::

package bean;

import java.io.*;

import java.util.*;

public class Ip{

static public HashMap ping; //ping 後的結果集

public HashMap getPing(){ //用來得到ping後的結果集

return ping;

}

//當前線程的數量, 防止過多線程摧毀電腦

static int threadCount = 0;

public Ip() {

ping = new HashMap();

}

public void Ping(String ip) throws Exception{

//最多30個線程

while(threadCount30)

Thread.sleep(50);

threadCount +=1;

PingIp p = new PingIp(ip);

p.start();

}

public void PingAll() throws Exception{

//首先得到本機的IP,得到網段

InetAddress host = InetAddress.getLocalHost();

String hostAddress = host.getHostAddress();

int k=0;

k=hostAddress.lastIndexOf(“.”);

String ss = hostAddress.substring(0,k+1);

for(int i=1;i =255;i++){ //對所有區域網Ip

String iip=ss+i;

Ping(iip);

}

//等著所有Ping結束

while(threadCount0)

Thread.sleep(50);

}

public static void main(String[] args) throws Exception{

Ip ip= new Ip();

ip.PingAll();

java.util.Set entries = ping.entrySet();

Iterator iter=entries.iterator();

String k;

while(iter.hasNext()){

Map.Entry entry=(Map.Entry)iter.next();

String key=(String)entry.getKey();

String value=(String)entry.getValue();

if(value.equals(“true”))

System.out.println(key+”–“+value);

}

}

class PingIp extends Thread{

public String ip; // IP

public PingIp(String ip){

this.ip=ip;

}

public void run(){

try{

Process p= Runtime.getRuntime().exec (“ping “+ip+ ” -w 300 -n 1″);

InputStreamReader ir = new InputStreamReader(p.getInputStream());

LineNumberReader input = new LineNumberReader (ir);

//讀取結果行

for (int i=1 ; i 7; i++)

input.readLine();

String line= input.readLine();

if (line.length() 17 || line.substring(8,17).equals(“timed out”))

ping.put(ip,”false”);

else

ping.put(ip,”true”);

//線程結束

threadCount -= 1;

}catch (IOException e){}

}

}

}

JAVA如何獲取客戶端IP地址和MAC地址

/**

* 獲取IP地址

* @return

*/

public static String GetNetIp() {

URL infoUrl = null;

InputStream inStream = null;

String line = “”;

try {

infoUrl = new URL(“”);

URLConnection connection = infoUrl.openConnection();

HttpURLConnection httpConnection = (HttpURLConnection) connection;

int responseCode = httpConnection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

inStream = httpConnection.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, “utf-8”));

StringBuilder strber = new StringBuilder();

while ((line = reader.readLine()) != null)

strber.append(line + “\n”);

inStream.close();

// 從反饋的結果中提取出IP地址

int start = strber.indexOf(“{“);

int end = strber.indexOf(“}”);

String json = strber.substring(start, end + 1);

if (json != null) {

try {

JSONObject jsonObject = new JSONObject(json);

line = jsonObject.optString(“cip”);

} catch (JSONException e) {

e.printStackTrace();

}

}

return line;

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return line;

}

public static String getLocalMacAddress() {//沒有緩存的地址,則查詢

String mac_s = “”; try { byte[] mac;

NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIpAddress()));

mac = ne.getHardwareAddress();

mac_s = byte2hex(mac);

} catch (Exception e) {

} mac_s; return mac_s;

}

java如何查詢本機ip地址和mac地址

// 獲取mac地址

  public static String getMacAddress() {

    try {

      EnumerationNetworkInterface allNetInterfaces = NetworkInterface.getNetworkInterfaces();

      byte[] mac = null;

      while (allNetInterfaces.hasMoreElements()) {

        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

        if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {

          continue;

        } else {

          mac = netInterface.getHardwareAddress();

          if (mac != null) {

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i  mac.length; i++) {

              sb.append(String.format(“%02X%s”, mac[i], (i  mac.length – 1) ? “-” : “”));

            }

            if (sb.length()  0) {

              return sb.toString();

            }

          }

        }

      }

    } catch (Exception e) {

      _logger.error(“MAC地址獲取失敗”, e);

    }

    return “”;

  }

 

  // 獲取ip地址

  public static String getIpAddress() {

    try {

      EnumerationNetworkInterface allNetInterfaces = NetworkInterface.getNetworkInterfaces();

      InetAddress ip = null;

      while (allNetInterfaces.hasMoreElements()) {

        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

        if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {

          continue;

        } else {

          EnumerationInetAddress addresses = netInterface.getInetAddresses();

          while (addresses.hasMoreElements()) {

            ip = addresses.nextElement();

            if (ip != null  ip instanceof Inet4Address) {

              return ip.getHostAddress();

            }

          }

        }

      }

    } catch (Exception e) {

      _logger.error(“IP地址獲取失敗”, e);

    }

    return “”;

  }

希望能幫助到你

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/160979.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-21 01:16
下一篇 2024-11-21 01:16

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • Python字元串寬度不限制怎麼打代碼

    本文將為大家詳細介紹Python字元串寬度不限制時如何打代碼的幾個方面。 一、保持代碼風格的統一 在Python字元串寬度不限制的情況下,我們可以寫出很長很長的一行代碼。但是,為了…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • cmd看地址

    本文將從多個方面詳細闡述cmd看地址,包括如何查看本機IP地址、如何查看路由器IP、如何查看DNS伺服器IP等等。 一、查看本機IP地址 要查看本機IP地址,首先需要打開cmd窗口…

    編程 2025-04-29
  • Java Bean載入過程

    Java Bean載入過程涉及到類載入器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean載入的過程。 一、類載入器 類載入器是Java虛擬機…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Python基礎代碼用法介紹

    本文將從多個方面對Python基礎代碼進行解析和詳細闡述,力求讓讀者深刻理解Python基礎代碼。通過本文的學習,相信大家對Python的學習和應用會更加輕鬆和高效。 一、變數和數…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發布。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29

發表回復

登錄後才能評論