티스토리 뷰

Storage

[IP Detection Program] IP 클래스 구분/식별 코드 in Java

rhys
반응형

IP Address Classes A-E


IP 주소의 다섯 클래스 A~E, 이를 분류해보자.






네트워크 관련 과제 중 멀티캐스트와 유니캐스트를 각기 다른 소켓으로 다루기 위해 찾았던 코드인데,


32개의 이진수로 표시되는 IP주소를 이용해 클래스를 구분한다.




  1. /*
  2. Program for IP (Internet Protocol) Class Detection in Java
  3. Author: Khushang Mehta Author Link: https://www.facebook.com/khushang.mehta
  4. www.pracspedia.com
  5. */
  6. class IpClassDetection
  7. {
  8. public static void main(String args[])
  9. {
  10. int ip[]=new int[4];
  11. int i=0,j=0,k=0,remainder;
  12. String bin;
  13. while(j!=3)
  14. {
  15. while(i < args[0].length() && args[0].charAt(i++)=='.')
  16. {
  17. ip[j++]=Integer.parseInt(args[0].substring(k,i-1));
  18. k=i;
  19. }
  20. }
  21. ip[j++]=Integer.parseInt(args[0].substring(k,args[0].length()));
  22. if(ip[0] >-1 &&ip[0] < 256 && ip[1] > -1 && ip[1] < 256 && ip[2] > -1 && ip[2] < 256 && ip[3] > -1 && ip[3] < 256)
  23. {
  24. System.out.println("Ip is valid");
  25. bin=Integer.toBinaryString(ip[0]);
  26. if(bin.charAt(0)=='0')
  27. {
  28. System.out.println("The Ip entered is a Class A Address");
  29. System.out.println("Net ID :- "+ip[0]);
  30. System.out.println("Host ID :- "+ip[1]+"."+ip[2]+"."+ip[3]);
  31. }
  32. else
  33. {
  34. if(bin.charAt(1)=='0')
  35. {
  36. System.out.println("The Ip entered is a Class B Address");
  37. System.out.println("Net ID :- "+ip[0]+"."+ip[1]);
  38. System.out.println("Host ID :- "+ip[2]+"."+ip[3]);
  39. }
  40. else
  41. {
  42. if(bin.charAt(2)=='0')
  43. {
  44. System.out.println("The Ip entered is a Class C Address");
  45. System.out.println("Net ID :- "+ip[0]+"."+ip[1]+"."+ip[2]);
  46. System.out.println("Host ID :- "+ip[3]);
  47. }
  48. else
  49. {
  50. if(bin.charAt(3)=='0')
  51. System.out.println("The Ip entered is a Class D Address");
  52. else
  53. System.out.println("The Ip entered is a Class E Address");
  54. }
  55. }
  56. }
  57. }
  58. else
  59. System.out.println("Ip is invalid");
  60. }
  61. }
  62. /*
  63. Output :-
  64. C:\Users\Student>java IpClassDetection 172.17.16.256
  65. Ip is invalid
  66.  
  67. C:\Users\Student>java IpClassDetection 172.17.16.52
  68. Ip is valid
  69. The Ip entered is a Class B Address
  70. Net ID :- 172.17
  71. Host ID :- 16.52
  72. */






반응형

댓글