บทความนี้อธิบายวิธีการรับที่อยู่ IP ของเซิร์ฟเวอร์และที่อยู่ MAC โดยการเขียนโปรแกรม Java แบ่งปันสำหรับการอ้างอิงของคุณดังนี้:
ระบบทดสอบ:
Windows Linux unix
ไม่รวม IPS ที่ผิดปกติเช่น 127.0.0.1 และ 0.0.0.1
นำเข้า java.net.inetaddress; นำเข้า java.net.networkinterface; นำเข้า java.net.socketexception; นำเข้า java.util.arraylist; นำเข้า java.util.en umeration; นำเข้า java.util.list; ) {} / ** * วิธีนี้อธิบาย: รับที่อยู่ IP ของเซิร์ฟเวอร์ * @author: [email protected] * @version: 5 กันยายน 2014 เวลา 4:57:15 น. * / สตริงคงที่สาธารณะ getLocalip () {String SIP = ""; ) {break;} NetworkInterface Ni = (NetworkInterface) NetInterfaces .nextElement (); if (! ip.isloopbackAddress () && ip.getHostaddress (). จับคู่ ("(//d {1,3}//. ) Break; / ** * วิธีนี้อธิบาย: รับที่อยู่ IP ของเซิร์ฟเวอร์ (การ์ดเครือข่ายหลายการ์ด) * @author: [email protected] * @version: 5 กันยายน 2014 เวลา 4:57:15 น. */ รายการคงที่สาธารณะ < String> getLocalips () {inemaddress ip = null; HasmoreElements ()) {NetworkInterface Ni = (NetworkInterface) NetInterfaces .nextElement (); if (! ip. isloopbackaddress () && ip.getHostaddress (). การจับคู่ ("(//d {1,3 }//. ) ip.getHostaddress ()); ของเซิร์ฟเวอร์ * @author: [email protected] * @version: 5 กันยายน 2014 เวลา 1:27:25 PM */ สตริงคงที่สาธารณะ getMacid () {String macid = ""; = null; ) NetInterfaces .nextElement (); ); ในขณะที่ (ips.hasmorelements ()) {ip = (inetaddress) ips.nextelement (); d {1,3} //.) {3}//d {1,3} ")) {bfindip = true; break;}}}}} catch (Exception e) {oututil.error (iputil.class, e.getMessage ()); ;}} return macid; : 25 pm */ รายการสาธารณะคงที่ <String> getMacids () {InetAddress IP = NULLINGINTERFACE NI = NULL; ne twininterface>) NetworkInterface .getNetWorkInterfaces (); คุณสามารถพิจารณาใช้ ni.getName เพื่อตัดสิน // ท่อง IPS การแจงนับทั้งหมด <inetaddress> ips = ni.getInetAdd resses () ในขณะที่ (ips.hasmorelements ()) {ip = (inetaddress) ips.nextelement (); ip.isloopbackaddress () // non-127.0.0.1 && ip.gethostaddress (). การจับคู่ ("(// d {1,3} //.) {3} // d {1,3}")) { maclist.add (getMacFrombytes (ni.gethardwareaddress ())); ไบต์ [] ไบต์) {StringBuffer MAC = New StringBuffer (); (B & 240) >> 4); } return mac.toString (). touppercase ();}}ฉันหวังว่าบทความนี้จะเป็นประโยชน์กับการเขียนโปรแกรม Java ของทุกคน