대학 생활/JAVA
[JAVA 코딩습관] IP주소는 하드코딩을 피해라.
opid
2014. 12. 31. 00:20
IP주소는 하드코딩을 피해라.
책 '자바 코딩, 이럴 땐 이렇게'에서 이번에도 꼭 알아두어야 할 것 같은 부분을 보고 남기려고 한다. 서버 프로그램을 작성할 때 서버의 IP를 소스코드에 하드코딩하는 습관이 바람직하지 않다고 한다.
첫 번째 이유는 관리적인 측면과 유지보수의 측면에서 볼 수 있다. 말 그대로 서버의 IP가 바뀌었거나, 소스 수정을 할 때 하나하나 찾아가며 바꿔야 하기 때문이다.
두 번째 이유는 보안적인 측면인데, 자바 소스는 디컴파일(decompile)이 가능하기 때문이다. 즉 JVM이 인식하는 코드 .class코드가 유출된다면 IP정보가 쉽게 유출된다는 점이다.
해결 방안
package Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Example {
private static final String DEFAULT_PROPERTIES_PATH = "d://test.properties";
private static String serverIP;
public static void main(String[] args) throws Exception {
setServerIP(Example.getKey("serverIp"));
}
public static String getKey(String key) throws Exception {
String value = null;
InputStream is = new FileInputStream(DEFAULT_PROPERTIES_PATH);
Properties properties = null;
try {
properties = new Properties();
properties.load(is);
value = properties.getProperty(key);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return value;
}
public static String getServerIP() {
return serverIP;
}
public static void setServerIP(String serverIP) {
Example.serverIP = serverIP;
}
}