เมื่อเร็ว ๆ นี้ฉันได้เรียนรู้ว่าการแปลงที่อยู่ IP เป็นทศนิยม, Octal และ Hexadecimal ยังสามารถเข้าถึงเว็บไซต์ได้
แปลง IP เป็นดิจิตอล (อัลกอริทึมที่สองใช้การเปลี่ยนแปลงซ้าย, bitwise หรือการใช้งานมีประสิทธิภาพมากขึ้น):
iptolong ยาวสาธารณะ (String iPaddress) {long result = 0; String [] iPaddressInarray = iPaddress.split ("//."); สำหรับ (int i = 3; i> = 0; i--) {long ip = long.parselong (ipaddressinarray [3-i]); // ซ้ายขยับ 24,16,8,0 และ bitwise หรือ // 1 192 << 24 // 1 168 << 16 // 1 1 << 8 // 1 2 << 0 ผลลัพธ์ | = IP << (i * 8); } ผลตอบแทนผลลัพธ์; -เมื่อตัวเลขถูกแปลงเป็น IP อัลกอริทึมทั้งสองจะคล้ายกัน:
// ip = 3232235778 สตริงสาธารณะ LongToip (ยาว IP) {StringBuilder result = new StringBuilder (15); สำหรับ (int i = 0; i <4; i ++) {result.insert (0, long.toString (IP & 0xff)); if (i <3) {result.insert (0, '.'); } IP = IP >> 8; } return result.toString (); } // ip = 3232235778 สตริงสาธารณะ LongToIP2 (Long IP) {return ((IP >> 24) & 0xff) + " + ((IP >> 16) & 0xff) + "." + ((IP >> 8) & 0xff) + "." + (IP & 0xff); -รหัสสมบูรณ์:
คลาสสาธารณะ JavabitWiseExample {โมฆะคงที่สาธารณะหลัก (สตริง [] args) {javabitWiseExample obj = ใหม่ javabitwiseExample (); System.out.println ("iptolong:" + obj.iptolong ("192.168.1.2")); System.out.println ("iptolong2:" + obj.iptolong2 ("192.168.1.2")); System.out.println ("longtoip:" + obj.longtoip (3232235778l)); System.out.println ("longtoip2:" + obj.longtoip2 (3232235778l)); } // ตัวอย่าง: 192.168.1.2 Iptolong สาธารณะยาว (สตริง ipaddress) {// ipaddressinarray [0] = 192 String [] iPaddressinarray = iPaddress.split ("//."); ผลลัพธ์ยาว = 0; สำหรับ (int i = 0; i <ipaddressinarray.length; i ++) {int power = 3 - i; int ip = integer.parseint (ipaddressinarray [i]); // 1. 192 * 256^3 // 2. 168 * 256^2 // 3. 1 * 256^1 // 4. 2 * 256^0 ผลลัพธ์ += ip * Math.pow (256, พลังงาน); } ผลตอบแทนผลลัพธ์; } public long iptolong2 (string ipaddress) {long result = 0; String [] iPaddressInarray = iPaddress.split ("//."); สำหรับ (int i = 3; i> = 0; i--) {long ip = long.parselong (ipaddressinarray [3-i]); // ซ้ายขยับ 24,16,8,0 และ bitwise or // 1. 192 << 24 // 1. 168 << 16 // 1. 1 << 8 // 1. 2 << 0 ผลลัพธ์ | = IP << (i * 8); } ผลตอบแทนผลลัพธ์; } สตริงสาธารณะ longtoip (ยาว i) {return ((i >> 24) & 0xff) + " + ((i >> 16) & 0xff) + "." + ((i >> 16) & 0xff) + "." + ((i >> 8) & 0xff) + "." + (i & 0xff); } สตริงสาธารณะ LongToIP2 (Long IP) {StringBuilder SB = ใหม่ StringBuilder (15); สำหรับ (int i = 0; i <4; i ++) {// 1. 2 // 2. 1 // 3. 168 // 4. 192 sb.insert (0, long.toString (IP & 0xff)); if (i <3) {sb.insert (0, '.'); } // 1. 192.168.1.2 // 2. 192.168.1 // 3. 192.168 // 4. 192 IP = IP >> 8; } return sb.toString (); -สรุป
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้เกี่ยวกับตัวอย่างการแปลงรหัสของที่อยู่และตัวเลข IP การเขียนโปรแกรม Java ฉันหวังว่ามันจะเป็นประโยชน์กับทุกคน เพื่อนที่สนใจสามารถอ้างถึงหัวข้ออื่น ๆ ที่เกี่ยวข้องในเว็บไซต์นี้ต่อไป หากมีข้อบกพร่องใด ๆ โปรดฝากข้อความไว้เพื่อชี้ให้เห็น!