티스토리 뷰

반응형

A. 아래의 코드를 사용하여 IP 주소를 숫자로 변환할 수 있습니다.

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPtoNumber {
  public static long ipToLong(String ipAddress) {
    try {
      InetAddress address = InetAddress.getByName(ipAddress);
      byte[] addressBytes = address.getAddress();
      long result = 0;
      for (int i = 0; i < addressBytes.length; i++) {
        result = (result << 8) | (addressBytes[i] & 0xff);
      }
      return result;
    } catch (UnknownHostException e) {
      throw new IllegalArgumentException("Invalid IP address: " + ipAddress);
    }
  }

  public static void main(String[] args) {
    String ipAddress = "192.168.1.1";
    long result = ipToLong(ipAddress);
    System.out.println("IP address: " + ipAddress + " is converted to number: " + result);
  }
}

 

Q. 숫자를 IP주소로 변환하는 함수를 자바로 만들어 줘?

 

A. 아래의 코드를 사용하여 숫자를 IP 주소로 변환할 수 있습니다.

import java.net.InetAddress;
import java.net.UnknownHostException;

public class NumberToIP {
  public static String longToIp(long i) {
    return ((i >> 24 ) & 0xFF) + "." +
           ((i >> 16 ) & 0xFF) + "." +
           ((i >> 8 ) & 0xFF) + "." +
           ( i & 0xFF);
  }

  public static void main(String[] args) {
    long number = 3232235777L;
    String result = longToIp(number);
    System.out.println("Number: " + number + " is converted to IP address: " + result);
  }
}
반응형