기본 콘텐츠로 건너뛰기

[자바] DATE, Calendar 객체 사용 예제

출처: http://blog.naver.com/PostView.nhn?blogId=pullpopo&logNo=40057609658&parentCategoryNo=23&viewDate=&currentPage=1&listtype=0

[ 날짜 연산법 ]
1. 시스템의 밀리초 구하기.(국제표준시각(UTC, GMT) 1970/1/1/0/0/0 으로부터 경과한 시각)
------------------------------------------------------------------
// 밀리초 단위(*1000은 1초), 음수이면 이전 시각
long time = System.currentTimeMillis ( ); 
System.out.println ( time.toString ( ) ); 
------------------------------------------------------------------
2. 현재 시각을 가져오기.
------------------------------------------------------------------
Date today = new Date (); 
System.out.println ( today );
결과 : Sat Jul 12 16:03:00 GMT+01:00 2000
------------------------------------------------------------------
3. 경과시간(초) 구하기
------------------------------------------------------------------
long time1 = System.currentTimeMillis (); 
long time2 = System.currentTimeMillis ();
system.out.println ( ( time2 - time1 ) / 1000.0 );
------------------------------------------------------------------
4. Date를 Calendar로 맵핑시키기
------------------------------------------------------------------
Date d = new Date ( );
Calendar c = Calendar.getInstance ( );
c.setTime ( d );
------------------------------------------------------------------
5. 날짜(년/월/일/시/분/초) 구하기
------------------------------------------------------------------
import java.util.*;
import java.text.*;
SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy.MM.dd HH:mm:ss", Locale.KOREA );
Date currentTime = new Date ( );
String dTime = formatter.format ( currentTime );
System.out.println ( dTime );
------------------------------------------------------------------
6. 날짜(년/월/일/시/분/초) 구하기2
------------------------------------------------------------------
GregorianCalendar today = new GregorianCalendar ( );
int year = today.get ( today.YEAR );
int month = today.get ( today.MONTH ) + 1;
int yoil = today.get ( today.DAY_OF_MONTH );
GregorianCalendar gc = new GregorianCalendar ( );
System.out.println ( gc.get ( Calendar.YEAR ) );
System.out.println ( String.valueOf ( gc.get ( Calendar.MONTH ) + 1 ) );
System.out.println ( gc.get ( Calendar.DATE ) );
System.out.println ( gc.get ( DAY_OF_MONTH ) );
------------------------------------------------------------------
7. 날짜(년/월/일/시/분/초) 구하기3
------------------------------------------------------------------
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.KOREA);
Calendar cal = Calendar.getInstance(Locale.KOREA);
nal = df.format(cal.getTime()); 
------------------------------------------------------------------
8. 표준시간대를 지정하고 날짜를 가져오기.
------------------------------------------------------------------
TimeZone jst = TimeZone.getTimeZone ("JST");
// 주어진 시간대에 맞게 현재 시각으로 초기화된 GregorianCalender 객체를 반환.
// 또는 Calendar now = Calendar.getInstance(Locale.KOREA);
Calendar cal = Calendar.getInstance ( jst );
System.out.println (
    cal.get ( Calendar.YEAR ) + "년 "
    + (cal.get ( Calendar.MONTH ) + 1) + "월 "
    + cal.get ( Calendar.DATE ) + "일 "
    + cal.get ( Calendar.HOUR_OF_DAY ) + "시 "
    + cal.get ( Calendar.MINUTE ) + "분 "
    + cal.get ( Calendar.SECOND ) + "초 " );
결과 : 2000년 8월 5일 16시 16분 47초 
------------------------------------------------------------------
9. 영어로된 날짜를 숫자로 바꾸기
------------------------------------------------------------------
Date myDate = new Date ( "Sun,5 Dec 1999 00:07:21" ); 
System.out.println ( myDate.getYear ( ) + "-" + myDate.getMonth ( ) + "-" + myDate.getDay ( ) ); 
------------------------------------------------------------------
10. "Sun, 5 Dec 1999 00:07:21"를 "1999-12-05"로 바꾸기
------------------------------------------------------------------
SimpleDateFormat formatter_one = new SimpleDateFormat ( "EEE, dd MMM yyyy hh:mm:ss",Locale.ENGLISH );
SimpleDateFormat formatter_two = new SimpleDateFormat ( "yyyy-MM-dd" );
String inString = "Sun, 5 Dec 1999 00:07:21";
ParsePosition pos = new ParsePosition ( 0 );
Date frmTime = formatter_one.parse ( inString, pos );
String outString = formatter_two.format ( frmTime );
System.out.println ( outString );
------------------------------------------------------------------
11. 숫자 12자리를, 다시 날짜로 변환하기
------------------------------------------------------------------
Date conFromDate = new Date();
long ttl = conFromDate.parse ( "Dec 25, 1997 10:10:10" );
System.out.println ( ttl ); //예 938291839221
Date today = new Date ( ttl );
DateFormat format = DateFormat.getDateInstance ( DateFormat.FULL,Locale.US );
String formatted = format.format ( today );
System.out.println ( formatted );
------------------------------------------------------------------
12. 특정일로부터 n일 만큼 이동한 날짜 구하기
------------------------------------------------------------------
특정일의 시간을 long형으로 읽어온다음..
날짜*24*60*60*1000 을 계산하여.
long형에 더해줍니다.
그리고 나서 Date클래스와 Calender클래스를 이용해서 날짜와 시간을 구하면 됩니다
------------------------------------------------------------------
13. 특정일에서 일정 기간후의 날짜 구하기2
------------------------------------------------------------------
//iDay 에 입력하신 만큼 빼거나 더한 날짜를 반환 합니다.
import java.util.*;
public String getDate ( int iDay ) 
{
    Calendar temp=Calendar.getInstance ( );
    StringBuffer sbDate=new StringBuffer ( );
    temp.add ( Calendar.DAY_OF_MONTH, iDay );
    int nYear = temp.get ( Calendar.YEAR );
    int nMonth = temp.get ( Calendar.MONTH ) + 1;
    int nDay = temp.get ( Calendar.DAY_OF_MONTH );
    sbDate.append ( nYear );
    if ( nMonth < 10 ) 
    sbDate.append ( "0" );
    sbDate.append ( nMonth );
    if ( nDay < 10 ) 
    sbDate.append ( "0" );
    sbDate.append ( nDay );
    return sbDate.toString ( );
}
------------------------------------------------------------------
14. 현재날짜에서 2달전의 날짜를 구하기
------------------------------------------------------------------
Calendar cal = Calendar.getInstance ( );//오늘 날짜를 기준으루..
cal.add ( cal.MONTH, -2 ); //2개월 전....
System.out.println ( cal.get ( cal.YEAR ) );
System.out.println ( cal.get ( cal.MONTH ) + 1 );
System.out.println ( cal.get ( cal.DATE ) );
------------------------------------------------------------------
15. 달에 마지막 날짜 구하기
------------------------------------------------------------------
for ( int month = 1; month <= 12; month++ ) 
{
    GregorianCalendar cld = new GregorianCalendar ( 2001, month - 1, 1 );
    System.out.println ( month + "/" + cld.getActualMaximum ( Calendar.DAY_OF_MONTH ) );
}
------------------------------------------------------------------
16. 해당하는 달의 마지막 일 구하기
------------------------------------------------------------------
GregorianCalendar today = new GregorianCalendar ( );
int maxday = today.getActualMaximum ( ( today.DAY_OF_MONTH ) );
System.out.println ( maxday );
------------------------------------------------------------------
17 특정일을 입력받아 해당 월의 마지막 날짜를 구하는 간단한 예제.(달은 -1 해준다.)...윤달 30일 31일 알아오기.
------------------------------------------------------------------
Calendar cal = Calendar.getInstance ( );
cal.set ( Integer.parseInt ( args[0] ), Integer.parseInt ( args [1] ) - 1, Integer.parseInt ( args [2] ) );
SimpleDateFormat dFormat = new SimpleDateFormat ( "yyyy-MM-dd" );
System.out.println ( "입력 날짜 " + dFormat.format ( cal.getTime ( ) ) );
System.out.println ( "해당 월의 마지막 일자 : " + cal.getActualMaximum ( Calendar.DATE ) );
------------------------------------------------------------------
18. 해당월의 실제 날짜수 구하기 ( 1999년 1월달의 실제 날짜수를 구하기 )
------------------------------------------------------------------
Calendar calendar = Calendar.getInstance ( );
calendar.set ( 1999, 0, 1 );
int maxDays = calendar.getActualMaximum ( Calendar.DAY_OF_MONTH );
------------------------------------------------------------------
19. 어제 날짜 구하기
------------------------------------------------------------------
오늘날짜를 초단위로 구해서 하루분을 빼주고 다시
셋팅해주면 쉽게 구할수 있죠..
setTime((기준일부터 오늘까지의 초를 구함) - 24*60*60)해주면 되겠죠..
------------------------------------------------------------------
20. 어제 날짜 구하기2
------------------------------------------------------------------
import java.util.*;
public static Date getYesterday ( Date today )
{
    if ( today == null ) 
    throw new IllegalStateException ( "today is null" );
    Date yesterday = new Date ( );
    yesterday.setTime ( today.getTime ( ) - ( (long) 1000 * 60 * 60 * 24 ) );
    return yesterday;
}
------------------------------------------------------------------
21. 내일 날짜 구하기
------------------------------------------------------------------
Date today = new Date ( );
Date tomorrow = new Date ( today.getTime ( ) + (long) ( 1000 * 60 * 60 * 24 ) );
------------------------------------------------------------------
22. 내일 날짜 구하기2
------------------------------------------------------------------
Calendar today = Calendar.getInstance ( );
today.add ( Calendar.DATE, 1 );
Date tomorrow = today.getTime ( );
------------------------------------------------------------------
23. 오늘날짜에서 5일 이후 날짜를 구하기
------------------------------------------------------------------
Calendar cCal = Calendar.getInstance();
c.add(Calendar.DATE, 5);
------------------------------------------------------------------
24. 날짜에 해당하는 요일 구하기
------------------------------------------------------------------
//DAY_OF_WEEK리턴값이 일요일(1), 월요일(2), 화요일(3) ~~ 토요일(7)을 반환합니다. 
//아래 소스는 JSP일부입니다.
import java.util.*;
Calendar cal= Calendar.getInstance ( );
int day_of_week = cal.get ( Calendar.DAY_OF_WEEK );
if ( day_of_week == 1 )
    m_week="일요일";
else if ( day_of_week == 2 )
    m_week="월요일";
else if ( day_of_week == 3 )
    m_week="화요일";
else if ( day_of_week == 4 )
    m_week="수요일";
else if ( day_of_week == 5 )
    m_week="목요일";
else if ( day_of_week == 6 )
    m_week="금요일";
else if ( day_of_week == 7 )
    m_week="토요일";
오늘은 : 입니다.
------------------------------------------------------------------
25. 콤보박스로 선택된 날짜(예:20001023)를 통해 요일을 영문으로 가져오기
------------------------------------------------------------------
//gc.get(gc.DAY_OF_WEEK); 하면 일요일=1, 월요일=2, ..., 토요일=7이 나오니까, 
//요일을 배열로 만들어서 뽑아내면 되겠죠. 
GregorianCalendar gc=new GregorianCalendar ( 2000, 10 - 1 , 23 ); 
String [] dayOfWeek = { "", "Sun", "Mon", .... , "Sat" }; 
String yo_il = dayOfWeek ( gc.get ( gc.DAY_OF_WEEK ) ); 
------------------------------------------------------------------
26. 두 날짜의 차이를 일수로 구하기
------------------------------------------------------------------
각각의 날짜를 Date형으로 만들어서 getTime()하면 
long으로 값이 나오거든요(1970년 1월 1일 이후-맞던가?- 1/1000 초 단위로..)
그러면 이값의 차를 구해서요. (1000*60*60*24)로 나누어 보면 되겠죠.
------------------------------------------------------------------
27. 두 날짜의 차이를 일수로 구하기2
------------------------------------------------------------------
import java.io.*;
import java.util.*;
Date today = new Date ( );
Calendar cal = Calendar.getInstance ( );
cal.setTime ( today );// 오늘로 설정.
Calendar cal2 = Calendar.getInstance ( );
cal2.set ( 2000, 3, 12 ); // 기준일로 설정. month의 경우 해당월수-1을 해줍니다.
int count = 0;
while ( !cal2.after ( cal ) )
{
    count++;
    cal2.add ( Calendar.DATE, 1 ); // 다음날로 바뀜
    System.out.println ( cal2.get ( Calendar.YEAR ) + "년 " + ( cal2.get ( Calendar.MONTH ) + 1 ) + "월 " + cal2.get ( Calendar.DATE ) + "일" );
}
System.out.println ( "기준일로부터 " + count + "일이 지났습니다." );
------------------------------------------------------------------
28. 두 날짜의 차이를 일수로 구하기3
------------------------------------------------------------------
import java.io.*;
import java.util.*;
public class DateDiff
{
    public static int GetDifferenceOfDate ( int nYear1, int nMonth1, int nDate1, int nYear2, int nMonth2, int nDate2 )
    {
        Calendar cal = Calendar.getInstance ( );
        int nTotalDate1 = 0, nTotalDate2 = 0, nDiffOfYear = 0, nDiffOfDay = 0;
        if ( nYear1 > nYear2 )
        {
            for ( int i = nYear2; i < nYear1; i++ ) 
            {
                cal.set ( i, 12, 0 );
                nDiffOfYear += cal.get ( Calendar.DAY_OF_YEAR );
            }
            nTotalDate1 += nDiffOfYear;
        }
        else if ( nYear1 < nYear2 )
        {
            for ( int i = nYear1; i < nYear2; i++ )
            {
                cal.set ( i, 12, 0 );
                nDiffOfYear += cal.get ( Calendar.DAY_OF_YEAR );
            }
            nTotalDate2 += nDiffOfYear;
        }
        cal.set ( nYear1, nMonth1-1, nDate1 );
        nDiffOfDay = cal.get ( Calendar.DAY_OF_YEAR );
        nTotalDate1 += nDiffOfDay;
        cal.set ( nYear2, nMonth2-1, nDate2 );
        nDiffOfDay = cal.get ( Calendar.DAY_OF_YEAR );
        nTotalDate2 += nDiffOfDay;
        return nTotalDate1-nTotalDate2;
    }
    public static void main ( String args[] )
    {
        System.out.println ( "" + GetDifferenceOfDate (2000, 6, 15, 1999, 8, 23 ) );
    }
}
------------------------------------------------------------------
29. 파일에서 날짜정보를 가져오기
------------------------------------------------------------------
File f = new File ( directory, file );
Date date = new Date ( f.lastModified ( ) );
Calendar cal = Calendar.getInstance ( );
cal.setTime ( date );
System.out.println("Year : " + cal.get(Calendar.YEAR));
System.out.println("Month : " + (cal.get(Calendar.MONTH) + 1));
System.out.println("Day : " + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("Hours : " + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("Minutes : " + cal.get(Calendar.MINUTE));
System.out.println("Second : " + cal.get(Calendar.SECOND));
------------------------------------------------------------------
30. 날짜형식으로 2000-01-03으로 처음에 인식을 시킨후
  7일씩 증가해서 1년정도의 날짜를 출력해 주고 싶은데요.
------------------------------------------------------------------
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-mm-dd" );
Calendar c = Calendar.getInstance ( );
for ( int i = 0; i < 48; i++ )
{
    c.clear ( );
    c.set ( 2000, 1, 3 - ( i * 7 ) );
    java.util.Date d = c.getTime ( );
    String thedate = sdf.format ( d );
    System.out.println ( thedate );

------------------------------------------------------------------
31. 쓰레드에서 날짜 바꾸면 죽는 문제
------------------------------------------------------------------
Main화면에 날짜와시간이Display되는 JPanel이 있습니다.
date로 날짜와 시간을 변경하면 Main화면의 날짜와 시간이 Display되는 Panel에 
변경된 날짜가 Display되지 않고 Main화면이 종료되어 버립니다.
문제소스:
public void run ( )
{
    while ( true )
    {
        try{
            timer.sleep ( 60000 );
        }
        catch ( InterruptedException ex ) { }
        lblTimeDate.setText ( fGetDateTime ( ) ); 
        repaint ( );
    }
}
public String fGetDateTime ( )
{
    final int millisPerHour = 60 * 60 * 1000;
    String DATE_FORMAT = "yyyy / MM / dd HH:mm";
    SimpleDateFormat sdf = new SimpleDateFormat ( DATE_FORMAT );
    SimpleTimeZone timeZone = new SimpleTimeZone ( 9 * millisPerHour, "KST" );
    sdf.setTimeZone ( timeZone );
    long time = System.currentTimeMillis ( );
    Date date = new Date ( time );
    return sdf.format ( date );
}
해답:
// 날짜와 요일 구한다. timezone 으로 날짜를 다시 셋팅하시면 됨니다.
public String getDate ( )
{
    Date now = new Date ( );
    SimpleDateFormat sdf4 = new SimpleDateFormat ( "yyyy/MM/dd HH:mm EE" );
    sdf4.setTimeZone ( TimeZone.getTimeZone ( "Asia/Seoul" ) );
    return sdf4.format ( now );
}
------------------------------------------------------------------
32. 날짜와 시간이 유효한지 검사하려면...?
------------------------------------------------------------------
import java.util.*;
import java.text.*;
public class DateCheck 
{
    boolean dateValidity = true;
    DateCheck ( String dt )
    { 
        try 
        {
            DateFormat df = DateFormat.getDateInstance ( DateFormat.SHORT );
            df.setLenient ( false ); 
            Date dt2 = df.parse ( dt ); 
        }
        catch ( ParseException e ) { this.dateValidity = false; }
        catch ( IllegalArgumentException e ) { this.dateValidity = false; }
    }
    public boolean datevalid ( )
    { 
        return dateValidity;
    }
    public static void main ( String args [] ) 
    {
        DateCheck dc = new DateCheck ( "2001-02-28" );
        System.out.println ( " 유효한 날짜 : " + dc.datevalid ( ) );
    }
}
------------------------------------------------------------------
33. 두 날짜 비교하기(아래보다 정확)
------------------------------------------------------------------
그냥 날짜 두개를 long(밀리 세컨드)형으로 비교하시면 됩니다...
이전의 데이타가 date형으로 되어 있다면, 이걸 long형으로 변환하고.
현재 날짜(시간)은 System.currentTimeMillis()메소드로 읽어들이고,
두수(long형)를 연산하여 그 결과 값으로 비교를 하시면 됩니다.
만약 그 결과값이 몇시간 혹은 며칠차이가 있는지를 계산할려면,
결과값을 Calender의 setTimeInMillis(long millis) 메소드를 이용해
설정한다음 각각의 날짜나 시간을 읽어오시면 됩니다
------------------------------------------------------------------
34. 두 날짜 비교하기2
------------------------------------------------------------------
//Calendar를 쓸 경우 데이타의 원본을 고치기 때문에 clone()을 사용하여 
//복사한 후에 그 복사본을 가지고 비교한다
import java.util.*;
import java.util.Calendar.*;
import java.text.SimpleDateFormat;
public class DayComparisonTest
{
    public static void main(String args[])
    {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat dateForm = new SimpleDateFormat("yyyy-MM-dd");
        Calendar aDate = Calendar.getInstance(); // 비교하고자 하는 임의의 날짜
        aDate.set(2001, 0, 1);
        Calendar bDate = Calendar.getInstance(); // 이것이 시스템의 날짜
        // 여기에 시,분,초를 0으로 세팅해야 before, after를 제대로 비교함
        aDate.set( Calendar.HOUR_OF_DAY, 0 );
        aDate.set( Calendar.MINUTE, 0 );
        aDate.set( Calendar.SECOND, 0 );
        aDate.set( Calendar.MILLISECOND, 0 );
        bDate.set( Calendar.HOUR_OF_DAY, 0 );
        bDate.set( Calendar.MINUTE, 0 );
        bDate.set( Calendar.SECOND, 0 );
        bDate.set( Calendar.MILLISECOND, 0 );

        if (aDate.after(bDate)) // aDate가 bDate보다 클 경우 출력
            System.out.println("시스템 날짜보다 뒤일 경우 aDate = " + dateForm.format(aDate.getTime())); 
        else if (aDate.before(bDate)) // aDate가 bDate보다 작을 경우 출력
            System.out.println("시스템 날짜보다 앞일 경우 aDate = " + dateForm.format(aDate.getTime()));
        else // aDate = bDate인 경우
            System.out.println("같은 날이구만");
    }
}



댓글

이 블로그의 인기 게시물

[인코딩] MS949부터 유니코드까지

UHC = Unified Hangul Code = 통합형 한글 코드 = ks_c_5601-1987 이는 MS사가 기존 한글 2,350자밖에 지원하지 않던 KS X 1001이라는 한국 산업 표준 문자세트를 확장해 만든 것으로, 원래 문자세트의 기존 내용은 보존한 상태로 앞뒤에 부족한 부분을 채워넣었다. (따라서 KS X 1001에 대한 하위 호환성을 가짐) 그럼, cp949는 무엇일까? cp949는 본래 코드 페이지(code page)라는 뜻이라 문자세트라 생각하기 십상이지만, 실제로는 인코딩 방식이다. 즉, MS사가 만든 "확장 완성형 한글 ( 공식명칭 ks_c_5601-1987 ) "이라는 문자세트를 인코딩하는 MS사 만의 방식인 셈이다. cp949 인코딩은 표준 인코딩이 아니라, 인터넷 상의 문자 송수신에 사용되지는 않는다. 하지만, "확장 완성형 한글" 자체가 "완성형 한글"에 대한 하위 호환성을 고려해 고안됐듯, cp949는 euc-kr에 대해 (하위) 호환성을 가진다. 즉 cp949는 euc-kr을 포괄한다. 따라서, 윈도우즈에서 작성되어 cp949로 인코딩 되어있는 한글 문서들(txt, jsp 등등)은 사실, euc-kr 인코딩 방식으로 인터넷 전송이 가능하다. 아니, euc-kr로 전송해야만 한다.(UTF-8 인코딩도 있는데 이것은 엄밀히 말해서 한국어 인코딩은 아니고 전세계의 모든 문자들을 한꺼번에 인코딩하는 것이므로 euc-kr이 한국어 문자세트를 인코딩할 수 있는 유일한 방식임은 변하지 않는 사실이다.) 물론 이를 받아보는 사람도 euc-kr로 디코딩을 해야만 문자가 깨지지 않을 것이다. KS X 1001을 인코딩하는 표준 방식은 euc-kr이며 인터넷 상에서 사용 가능하며, 또한 인터넷상에서 문자를 송수신할때만 사용.(로컬하드에 저장하는데 사용하는 인코딩방식으로는 쓰이지 않는 듯하나, *nix계열의 운영체제에서는 LANG을 euc-kr로 설정 가능하기도 한걸

[linux] 뻔하지 않은 파일 퍼미션(file permissions) 끄적임. 정말 속속들이 아니?

1. [특수w]내 명의의 디렉토리라면 제아무리 루트가 만든 파일에 rwxrwxrwx 퍼미션이라 할지라도 맘대로 지울 수 있다. 즉 내 폴더안의 파일은 뭐든 지울 수 있다. 2. [일반rx]하지만 읽기와 쓰기는 other의 권한을 따른다. 3.[일반rwx]단 남의 계정 폴더는 그 폴더의 퍼미션을 따른다. 4.[일반]만약 굳이 sudo로 내 소유로 파일을 넣어놓더라도 달라지는건 없고, 단지 그 폴더의 other퍼미션에 write권한이 있으면 파일을 만들고 삭제할 수 있다. 5.디렉토리의 r권한은 내부의 파일이름 정도만 볼 수있다. 하지만 ls 명령의 경우 소유자, 그룹, 파일크기 등의 정보를 보는 명령어므로 정상적인 실행은 불가능하고, 부분적으로 실행됨. frank@localhost:/export/frankdir$ ls rootdir/ ls: cannot access rootdir/root: 허가 거부 ls: cannot access rootdir/fa: 허가 거부 fa  root #이처럼 속한 파일(폴더)만 딸랑 보여준다. frank@localhost:/export/frankdir$ ls -al rootdir/ # al옵션이 모두 물음표 처리된다.. ls: cannot access rootdir/root: 허가 거부 ls: cannot access rootdir/..: 허가 거부 ls: cannot access rootdir/.: 허가 거부 ls: cannot access rootdir/fa: 허가 거부 합계 0 d????????? ? ? ? ?             ? . d????????? ? ? ? ?             ? .. -????????? ? ? ? ?             ? fa -????????? ? ? ? ?             ? root 하지만 웃긴건, r에는 읽기 기능이 가능하므로 그 폴더 안으로 cd가 되는 x권한이 없더라도 어떤 파일이 있는지 목록 정도는 알 수 있다. 하지만 r이라고

[hooking, 후킹, 훅킹] Hooking이란?

source: http://jinhokwon.blogspot.kr/2013/01/hooking.html Hooking 이란? [출처] http://blog.daum.net/guyya/2444691 훅킹(Hooking)이란 이미 작성되어 있는 코드의 특정 지점을 가로채서 동작 방식에 변화를 주는 일체의 기술 이다. 훅이란 낚시바늘같은 갈고리 모양을 가지는데 여기서는 코드의 중간 부분을 낚아채는 도구라는 뜻으로 사용된다. 대상 코드의 소스를 수정하지 않고 원하는 동작을 하도록 해야 하므로 기술적으로 어렵기도 하고 운영체제의 통상적인 실행 흐름을 조작해야 하므로 때로는 위험하기도 하다. 훅킹을 하는 방법에는 여러 가지가 있는데 과거 도스 시절에 흔히 사용하던 인터럽터 가로채기 기법이나 바로 앞에서 알아본 서브클래싱도 훅킹 기법의 하나라고 할 수 있다. 이외에도 미리 약속된 레지스트리 위치에 훅 DLL의 이름을 적어 주거나 BHO(Browser Helper Object)나 응용 프로그램 고유의 추가 DLL(Add in)을 등록하는 간단한 방법도 있고 PE 파일의 임포트 함수 테이블을 자신의 함수로 변경하기, CreateRemoteThread 함수로 다른 프로세스의 주소 공간에 DLL을 주입(Injection)하는 방법, 메모리의 표준 함수 주소를 덮어 쓰는 꽤 어려운 방법들도 있다. 이런 고급 훅킹 기술은 이 책의 범위를 벗어나므로 여기서는 소개만 하고 다루지는 않기로 한다. 이 절에서 알아볼 메시지 훅은 윈도우로 전달되는 메시지를 가로채는 기법으로 다양한 훅킹 방법중의 하나이다. 메시지 기반의 윈도우즈에서는 운영체제와 응용 프로그램, 또는 응용 프로그램 사이나 응용 프로그램 내부의 컨트롤끼리도 많은 메시지들을 주고 받는다. 훅(Hook)이란 메시지가 목표 윈도우로 전달되기 전에 메시지를 가로채는 특수한 프로시저이다. 오고 가는 메시지를 감시하기 위한 일종의 덫(Trap)인 셈인데 일단 응용 프로그램이 훅 프로시저를 설치하면 메시지가 윈도우로 보내지기