태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.

사이드바 열기

'a tip-off'에 해당되는 글 30건

=== FRAME ===

 

above : 바깥 테두리를(이하 생략) 위쪽만 표시


below :  아래쪽만 표시


border or box : 모두 표시


lhs : 왼쪽만 표시


rhs : 오른쪽만 표시


hsides : 세로선 ( 왼/오른쪽 ) 만 표시


vsides : 가로선 ( 위/아래 ) 만 표시


void : 테두리 표시 안함


ex )

<table border="1" frame="below" cellpadding="0" cellspacing="0">


=== RULES ===


all : 안쪽 테두리를 ( 이하 생략 ) 모두 표시


cols : 칸 구분선만 표시


rows : 줄 구분선만 표시


groups : 그룹요소들의 안쪽 테두리만 표시


none : 표시 안함


<table border="1" rules="all" cellpadding="0" cellspacing="0">

Posted by heresyrt
 

Oracle 10g Simplified Shared Server Configuration

In Oracle 10g, you no longer need to set as many initialization parameters for shared server environments. In fact, you only need to set one parameter if you are using TCP/IP as your communication protocol, and the rest of the settings are now managed internally.

Shared Server Initialization Parameters

The following initialization parameters in Oracle 10g control shared server operation:

shared_servers – This parameter specifies the initial number of shared servers to start and the minimum number of shared servers to keep. This is the only required parameter for using shared servers. Setting this to a non-zero value automatically specifies shared server.

max_shared_servers – This parameter specifies the maximum number of shared servers that can run simultaneously. Once shared server is initialized, the Oracle system will increase the number of shared servers up to this value as needed.

shared_server_sessions -- This parameter specifies the total number of shared server user sessions that can run simultaneously. Setting this parameter enables you to reserve user sessions for dedicated servers. For example, if the sessions parameter is set at 1000 and you set shared_server_sessions to 900, then 100 dedicated sessions are available, even if all 900 shared sessions are in use.

dispatchers – This parameter configures dispatcher processes in the shared server architecture. One dispatcher is always configured by default for the TCP/IP protocol, even if the parameter is not explicitly specified.

max_dispatchers – This parameter specifies the maximum number of dispatcher processes that can run simultaneously. According to the Oracle 10g manuals, this parameter can be ignored for now. It will only be useful in a future release when the number of dispatchers is auto-tuned, according to the number of concurrent connections.

circuits – This parameter specifies the total number of virtual circuits that are available for inbound and outbound network sessions.

Even though there are six initialization parameters, shared server is enabled by setting one parameter and is turned on if the shared_servers initialization parameter is set to a value greater than 0. This is all that is required. The other shared server initialization parameters do not need to be set. Because the shared server parameter requires at least one dispatcher to work, a dispatcher is brought up automatically even when no dispatcher has been configured.

Using SQL*Plus or OEM, the shared server features can be started dynamically by setting the shared_servers parameter to a nonzero value


Get the complete Oracle10g story:

The above text is an excerpt from "Oracle Database 10g New Features: Oracle10g Reference for Advanced Tuning and Administration", by Rampant TechPress.  Written by top Oracle experts, this book has a complete online code deport with ready to use scripts. 

 

 

The switch from dedicated server to shared server is easy. You begin by editing the init.ora file for your instance. You will need to either add in a line for dispatchers, or edit the existing line (When creating a database with DBCA on Windows, Oracle adds in a line even if you don't request dispatchers. So, be aware of the fact that you may just be changing that line).
At minimum, you will need:
    dispatchers="(protocol=tcp)"
A more complete configuration would be:
    dispatchers="(protocol=tcp)(dispatchers=2)(service=mydatabase)"
The (dispatchers=2) that you see tells oracle to spawn 2 dispatchers at startup.

Configuring dispatchers can get more elaborate. Unless you have experience and documentation for setting up a more advanced configuration, it is probably better to allow Oracle to give you default values for everything else. A complete list of possible dispatcher parameters is here:

dispatch_clause::= (PROTOCOL = protocol) | (ADDRESS = address) | (DESCRIPTION = description ) [options_clause] options_clause::= (DISPATCHERS = integer | SESSIONS = integer | CONNECTIONS = integer | TICKS = seconds | POOL = {1 | ON | YES | TRUE | BOTH | ({IN | OUT} = ticks) | 0 | OFF | NO | FALSE | ticks} | MULTIPLEX = {1 | ON | YES | TRUE | 0 | OFF | NO | FALSE | BOTH | IN | OUT} | LISTENER = tnsname | SERVICE = service | INDEX = integer ) 
There are some other parameters you will likely want to set as long as you are working on dispatchers. Here is an example:
########################################### # DISPATCHERS ########################################### dispatchers="(protocol=tcp)(dispatchers=2)(service=test)" ## shared servers on startup shared_servers=2 ## maximum shared server sessions shared_server_sessions=200 ## Maximum Shared Servers max_shared_servers=20 ## Maximum Dispatchers max_dispatchers=20 
Once you have changed your init.ora file and bounced your database, how can you tell if connections are going through dispatchers? There are a number of dynamic performance views that can tell you this, for example v$session, v$dispatcher, v$queue. To keep things easy, I just create my own view that gives me the data I like to see:
CREATE OR REPLACE FORCE VIEW SYSTEM.CURRENT_CONNECTIONS (SID, SERIAL#, USERNAME, OSUSER, STATUS, "SCNDS NOT ACTIVE", DISPATCHER) AS SELECT /* ©2004 by Edward Stoever, edward@database-expert.com */  s.SID, s.serial#, s.username, s.osuser, s.status, DECODE (s.username, NULL, 0, s.last_call_et) "SCNDS NOT ACTIVE", NVL (d.NAME, 'none') "DISPATCHER" FROM v$session s, v$dispatcher d WHERE s.paddr = d.paddr(+) ORDER BY status ASC, last_call_et ASC; CREATE PUBLIC SYNONYM CURRENT_CONNECTIONS FOR SYSTEM.CURRENT_CONNECTIONS; 
Sample output:
select * from system.current_connections; SID SERIAL# USERNAME OSUSER STATUS SCNDS NOT ACTIVE DISPAT ------ ------- ------------ ------------ -------- ---------------- ------ 15 167 SYSTEM STOEVER ACTIVE 0 none 11 10 GENERAL GURJOBS_TEST ACTIVE 12535 none 1 1 @ ORACLE ACTIVE 0 none 2 1 @ ORACLE ACTIVE 0 none 3 1 @ ORACLE ACTIVE 0 none 4 1 @ ORACLE ACTIVE 0 none 5 1 @ ORACLE ACTIVE 0 none 6 1 @ ORACLE ACTIVE 0 none 7 1 @ ORACLE ACTIVE 0 none 8 1 @ ORACLE ACTIVE 0 none 18 176 WTAILOR jbautista INACTIVE 12 D000 16 191 WTAILOR jbautista INACTIVE 132 D001 10 212 WTAILOR jbautista INACTIVE 134 D001 13 119 WEB_USER SYSTEM INACTIVE 314 D000 14 20 SYSTEM vlugo INACTIVE 721 D001 
Now you can see who is connecting and how, either via a dispatcher or via a dedicated connection.
Does this mean that all connections from now on will be through a dispatcher? No. There are plenty of cases in which you will want or even require a connection that is dedicated. For example, to shutdown the database, a dedicated connection is required. Also, many processes are recource intensive and will perform better with a dedicated connection. To create a dedicated connection, you will need to edit the TNSNAMES.ORA file on the machine from which the connection originates. Here is an example:
### SHARED CONNECTION TO TEST DATABASE TEST_SHARED = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = alpha2)(PORT = 1521)) ) (CONNECT_DATA = (SERVER = SHARED) (SERVICE_NAME = test) ) ) ### DEDICATED CONNECTION TO TEST DATABASE TEST_DEDICATED = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = alpha2)(PORT = 1521)) ) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = test) ) ) 
Now, to connect via a dispatcher, try this:
SQLPLUS scott/tiger@test_shared
to connect via a dedicated server process, try this:
SQLPLUS scott/tiger@test_dedicated
이올린에 북마크하기(0) 이올린에 추천하기(0)
Posted by heresyrt

File 클래스

 File클래스에는 일반 파일을 생성하는 기능을 제외한 이미 존재하는 파일에 대한 제어나 특수한 파일인 디렉토리를 생성하는 기능이 지원된다. 파일이라는 객체와 관련된 동작에 대한 메서드들은 모두 이 클래스에서 지원된다.


>>> File
클래스 관련 예제 (파일이 있는지 없는지 확인)<<<

import java.io.*;

import java.util.*;

public class FileInfo{

    public static void main(String args[]){

        File f=new File("D:/StudyII/Java/Example/File",args[0]);

        if(f.exists())            //파일이 존재하면

            System.out.println("Existed!!");

        else

            System.out.println("Not Found!!");

        }

   }

결과

c:\Test>jva FileInfo 파일명

있으면 ?? 없으면 ??


>>> File클래스 관련 예제 (디렉토리 안의 파일 열기)<<<

import java.io.*;

import java.util.*;

public class FileInfo2{

    public static void main(String args[]){

        File f=new File(args[0]);

        if(f.isDirectory()){

            String list[]=f.list();

            for(int i=0; i<list.length; i++)

                System.out.println(list[i]);

        }else

                System.out.println("Not a Directory!!");

    }

}

결과

c:\Test>java FileInfo2 Test

Test가 디렉토리라면 디렉토리 안의 파일 열거

Test가 디렉토리가 아니면 Not a Directory


>>> File클래스 관련 문제 (마지막 수정된 날짜 표시하기)<<<

import java.io.*;

import java.util.*;

public class FileTest1{

    public static void main(String args[]){

        File f=new File("D:/StudyII/Java/Example/File/Test");

        File[] contents=f.listFiles();

        System.out.println("File디렉토리에 들어있는 "+contents.length+"개의 항목");

      

        for(int i=0; i<contents.length; i++){

            System.out.println(contents[i]+""+new Date(contents[i].lastModified())+"에 수정된 "+

            (contents[i].isDirectory()?"디렉토리이다.":"파일이다.")

    );
        }
    }

}


>>> File클래스 관련 문제 <<<

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Lab1 : 구구단을 출력할 파일명과 단을 각각 인수로 입력받아 File클래스를 이용하여 파일을

생성하고 새로운 파일에 구구단이 아래와 같이 출력되는 소스를 작성한다.

---------------------------------------------------------------------------------------------------------

c:\Test>java FileTest2 2 2Dan.txt
< 2Dan.txt >안에 2단 구구단 출력
---------------------------------------------------------------------------------------------------------
import java.io.*;

import java.util.*;

public class FileTest2{

    public static void main(String args[]){

        String dan=args[0];

        try{

            FileWriter bw=new FileWriter(args[1]);

            for(int i=1; i<10; i++){

            bw.write(dan+"*"+i+"="+(Integer.parseInt(dan)*i)+"\n");

                }

            bw.close();

        }catch(IOException e){

            System.out.println(e);

        }

    }

}


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Lab2 : 디렉토리명을 사용자로부터 입력받아 아래처럼 디렉토리를 생성하는 소스를 작성한다.

--------------------------------------------------------------------------------------------------------------------

import java.io.*;

class Test{

    public static void main(String args[]) throws IOException{

       System.out.println("디렉토리 생성하기!");

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        String directoryName=br.readLine();

        File f=new File(directoryName);

        if(f.mkdir()){

            System.out.println("디렉토리 '"+directoryName+"' 생성됨!");

        }else{

            System.out.println("디렉토리 '"+directoryName+"' 생성되지 않음!");

        }

    }

}


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Lab3 : 아래와 같이 출력되도록 소스를 작성한다.

---------------------------------------------------------------------------------------------------------

c:\Test>java Test
파일경로구분자 ==> ;
디렉토리구분자 ==> \
루트 디렉토리 ==> C:\
루트 디렉토리 ==> D:\
현재 디렉토리 ==> C:\\.
----------------------------------------------------------------------------------------------------------
import java.io.*;

public class Test{

    public static void main(String args[]){

        System.out.println("파일경로구분자 ==> "+File.pathSeparator);

        System.out.println("디렉토리구분자 ==> "+File.separator);

        File[] root=File.listRoots();

        for(File f:root){

            System.out.println("루트 디렉토리 ==> "+f);

        }

        System.out.println("현재 디렉토리 ==> "+new File(".").getAbsolutePath());

    }

}


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Lab3 : 아래 실행결과처럼 Root File(드라이버명)file, 디렉토리명이 찍히도록 소스를 작성한다.

, 디렉토리는 대괄호를 씌워서 구분짓는다. 모든 드라이버명 다 출력

---------------------------------------------------------------------------------------------------------

c:\Test>java ExListRoots
A:\
C:\
       abc.txt
       [AromaWIPI]
       boot.ini
----------------------------------------------------------------------------------------------------------

import java.io.*;

class ExListRoots{

public static void main(String args[]){

File[] rootFile=File.listRoots();

for(int i=0; i<rootFile.length; i++){

System.out.println(rootFile[i]);

if(rootFile[i].toString().startsWith("C:")){

File[] fileName=rootFile[i].listFiles();

for(int j=0; j<fileName.length; j++){

if(fileName[j].isFile())

                                        System.out.println("\t"+fileName[j].getName());

else

                                         System.out.println("\t["+fileName[j].getName()+"]");

}

}

}

}

}

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Lab4 : 파일의 확장명이 java인것 파일만 출력되도록 소스를 작성한다.

---------------------------------------------------------------------------------------------------------

import java.io.*;
public class FileTest{
    public static void main(String args[]) throws Exception{
        File f=new File("c:\\");
        String files[]=f.list();
        for(int i=0 ; i<files.length ; i++){
            if(files[i].endsWith(".java"))
                System.out.println(files[i]);
            }
        }
}


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Lab5 : 파일이름에 “Li”를 포함하는 파일만 출력되도록 소스를 작성한다.

---------------------------------------------------------------------------------------------------------

import java.io.*;

public class FileTest{

    public static void main(String args[]) throws Exception{

        File f=new File("c:\\");

        String files[]=f.list();

for(int i=0; i<files.length; i++){

if(files[i].indexOf("Li") != -1)      //indexOf()가 -1이면 찾는 문자열이 없음

                                                                System.out.println(files[i]);

}

}

}


FilenameFilter

 파일의 이름을 필터링할 수 있는 기능을 가진 인터페이스

만약 어떤 디렉토리의 파일들의 목록을 읽어서 확장자가 .java로 끝나는 파일들만 검색하고 싶다면 다음과 같이 해주어야 한다.

FilenameFilter인터페이스를 구현하는 클래스를 만들고 accept()를 만든다.

File객체의 list()를 이용해서 원하는 디렉토리의 해당 파일 목록을 구한다.


>>> FilenameFilter인터페이스 관련 예제 <<<

import java.io.*;

class MyFilter implements FilenameFilter{

    public boolean accept(File dir, String fileName){

        return fileName.endsWith(".java");

        }

    }

public class FilterEx{

    public static void main(String args[]){

        FilterEx fe=new FilterEx();

        fe.test();

    }

    public void test(){

        File dir=new File("c:\Test");

        MyFilter filter=new MyFilter();

        File[] files=dir.listFiles(filter);

        for(int i=0; i<files.length; i++)

            System.out.println("File Name : "+files[i].getName());

    }

}

결과

c:\Test>java FileterEx

File Name : TbarApplet.java


>>> FilenameFilter인터페이스 관련 예제 <<<

import java.io.*;

class MyFilter implements FilenameFilter{

    private String keyword;

    private String fileExt;

   

    public MyFilter(String keyword, String fileExt){

        this.keyword=keyword;

        this.fileExt=fileExt;

    }

    public boolean accept(File dir, String fileName){

        if(fileExt.equals("all"))

            fileExt="\\w*";

        return fileName.matches("\\w*"+keyword+"\\w*."+fileExt);

    }

}

public class FilterEx{

    public static void main(String args[]){

        FilterEx fe=new FilterEx();

        fe.test();

    }

    public void test(){

        File dir=new File("c:\Test");

        MyFilter filter=new MyFilter("Test","java");

        File[] files=dir.listFiles(filter);

        for(int i=0; i<files.length; i++)

            System.out.println("File Name : "+files[i].getName());

    }

}

결과

c:\Test>java FileterEx

File Name : ArrayTest.java

File Name : EventTest.java

이올린에 북마크하기(0) 이올린에 추천하기(0)
Posted by heresyrt

TCPDUMP

a tip-off 2008/02/01 09:53

TCPDUMP

Section: User Commands (1)
Updated: 15 June 2007

 

NAME

tcpdump - dump traffic on a network  

SYNOPSIS

tcpdump [ -AdDefKlLnNOpqRStuUvxX ] [ -c count ]

         [ -C file_size ] [ -G rotate_seconds ] [ -F file ]

         [ -i interface ] [ -m module ] [ -M secret ]

         [ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]

         [ -W filecount ]

         [ -E spi@ipaddr algo:secret,... ]

         [ -y datalinktype ] [ -z postrotate-command ] [ -Z user ]
         [ expression ]
 

DESCRIPTION

Tcpdump prints out a description of the contents of packets on a network interface that match the boolean expression. It can also be run with the -w flag, which causes it to save the packet data to a file for later analysis, and/or with the -r flag, which causes it to read from a saved packet file rather than to read packets from a network interface. In all cases, only packets that match expression will be processed by tcpdump.

Tcpdump will, if not run with the -c flag, continue capturing packets until it is interrupted by a SIGINT signal (generated, for example, by typing your interrupt character, typically control-C) or a SIGTERM signal (typically generated with the kill(1) command); if run with the -c flag, it will capture packets until it is interrupted by a SIGINT or SIGTERM signal or the specified number of packets have been processed.

When tcpdump finishes capturing packets, it will report counts of:

packets ``captured'' (this is the number of packets that tcpdump has received and processed);
packets ``received by filter'' (the meaning of this depends on the OS on which you're running tcpdump, and possibly on the way the OS was configured - if a filter was specified on the command line, on some OSes it counts packets regardless of whether they were matched by the filter expression and, even if they were matched by the filter expression, regardless of whether tcpdump has read and processed them yet, on other OSes it counts only packets that were matched by the filter expression regardless of whether tcpdump has read and processed them yet, and on other OSes it counts only packets that were matched by the filter expression and were processed by tcpdump);
packets ``dropped by kernel'' (this is the number of packets that were dropped, due to a lack of buffer space, by the packet capture mechanism in the OS on which tcpdump is running, if the OS reports that information to applications; if not, it will be reported as 0).

On platforms that support the SIGINFO signal, such as most BSDs (including Mac OS X) and Digital/Tru64 UNIX, it will report those counts when it receives a SIGINFO signal (generated, for example, by typing your ``status'' character, typically control-T, although on some platforms, such as Mac OS X, the ``status'' character is not set by default, so you must set it with stty(1) in order to use it) and will continue capturing packets.

Reading packets from a network interface may require that you have special privileges:

Under SunOS 3.x or 4.x with NIT or BPF:
You must have read access to /dev/nit or /dev/bpf*.
Under Solaris with DLPI:
You must have read/write access to the network pseudo device, e.g. /dev/le. On at least some versions of Solaris, however, this is not sufficient to allow tcpdump to capture in promiscuous mode; on those versions of Solaris, you must be root, or tcpdump must be installed setuid to root, in order to capture in promiscuous mode. Note that, on many (perhaps all) interfaces, if you don't capture in promiscuous mode, you will not see any outgoing packets, so a capture not done in promiscuous mode may not be very useful.
Under HP-UX with DLPI:
You must be root or tcpdump must be installed setuid to root.
Under IRIX with snoop:
You must be root or tcpdump must be installed setuid to root.
Under Linux:
You must be root or tcpdump must be installed setuid to root (unless your distribution has a kernel that supports capability bits such as CAP_NET_RAW and code to allow those capability bits to be given to particular accounts and to cause those bits to be set on a user's initial processes when they log in, in which case you must have CAP_NET_RAW in order to capture and CAP_NET_ADMIN to enumerate network devices with, for example, the -D flag).
Under ULTRIX and Digital UNIX/Tru64 UNIX:
Any user may capture network traffic with tcpdump. However, no user (not even the super-user) can capture in promiscuous mode on an interface unless the super-user has enabled promiscuous-mode operation on that interface using pfconfig(8), and no user (not even the super-user) can capture unicast traffic received by or sent by the machine on an interface unless the super-user has enabled copy-all-mode operation on that interface using pfconfig, so useful packet capture on an interface probably requires that either promiscuous-mode or copy-all-mode operation, or both modes of operation, be enabled on that interface.
Under BSD (this includes Mac OS X):
You must have read access to /dev/bpf* on systems that don't have a cloning BPF device, or to /dev/bpf on systems that do. On BSDs with a devfs (this includes Mac OS X), this might involve more than just having somebody with super-user access setting the ownership or permissions on the BPF devices - it might involve configuring devfs to set the ownership or permissions every time the system is booted, if the system even supports that; if it doesn't support that, you might have to find some other way to make that happen at boot time.

Reading a saved packet file doesn't require special privileges.  

OPTIONS

-A
Print each packet (minus its link level header) in ASCII. Handy for capturing web pages.
-c
Exit after receiving count packets.
-C
Before writing a raw packet to a savefile, check whether the file is currently larger than file_size and, if so, close the current savefile and open a new one. Savefiles after the first savefile will have the name specified with the -w flag, with a number after it, starting at 1 and continuing upward. The units of file_size are millions of bytes (1,000,000 bytes, not 1,048,576 bytes).
-d
Dump the compiled packet-matching code in a human readable form to standard output and stop.
-dd
Dump packet-matching code as a C program fragment.
-ddd
Dump packet-matching code as decimal numbers (preceded with a count).
-D
Print the list of the network interfaces available on the system and on which tcpdump can capture packets. For each network interface, a number and an interface name, possibly followed by a text description of the interface, is printed. The interface name or the number can be supplied to the -i flag to specify an interface on which to capture.
This can be useful on systems that don't have a command to list them (e.g., Windows systems, or UNIX systems lacking ifconfig -a); the number can be useful on Windows 2000 and later systems, where the interface name is a somewhat complex string.
The -D flag will not be supported if tcpdump was built with an older version of libpcap that lacks the pcap_findalldevs() function.
-e
Print the link-level header on each dump line.
-E
Use spi@ipaddr algo:secret for decrypting IPsec ESP packets that are addressed to addr and contain Security Parameter Index value spi. This combination may be repeated with comma or newline seperation.
Note that setting the secret for IPv4 ESP packets is supported at this time.
Algorithms may be des-cbc, 3des-cbc, blowfish-cbc, rc3-cbc, cast128-cbc, or none. The default is des-cbc. The ability to decrypt packets is only present if tcpdump was compiled with cryptography enabled.
secret is the ASCII text for ESP secret key. If preceeded by 0x, then a hex value will be read.
The option assumes RFC2406 ESP, not RFC1827 ESP. The option is only for debugging purposes, and the use of this option with a true `secret' key is discouraged. By presenting IPsec secret key onto command line you make it visible to others, via ps(1) and other occasions.
In addition to the above syntax, the syntax file name may be used to have tcpdump read the provided file in. The file is opened upon receiving the first ESP packet, so any special permissions that tcpdump may have been given should already have been given up.
-f
Print `foreign' IPv4 addresses numerically rather than symbolically (this option is intended to get around serious brain damage in Sun's NIS server --- usually it hangs forever translating non-local internet numbers).
The test for `foreign' IPv4 addresses is done using the IPv4 address and netmask of the interface on which capture is being done. If that address or netmask are not available, available, either because the interface on which capture is being done has no address or netmask or because the capture is being done on the Linux "any" interface, which can capture on more than one interface, this option will not work correctly.
-F
Use file as input for the filter expression. An additional expression given on the command line is ignored.
-G
If specified, rotates the dump file specified with the -w option every rotate_seconds seconds. Savefiles will have the name specified by -w which should include a time format as defined by strftime(3). If no time format is specified, each new file will overwrite the previous.
If used in conjunction with the -C option, filenames will take the form of `file<count>'.
-i
Listen on interface. If unspecified, tcpdump searches the system interface list for the lowest numbered, configured up interface (excluding loopback). Ties are broken by choosing the earliest match.
On Linux systems with 2.2 or later kernels, an interface argument of ``any'' can be used to capture packets from all interfaces. Note that captures on the ``any'' device will not be done in promiscuous mode.
If the -D flag is supported, an interface number as printed by that flag can be used as the interface argument.
-K
Don't attempt to verify TCP checksums. This is useful for interfaces that perform the TCP checksum calculation in hardware; otherwise, all outgoing TCP checksums will be flagged as bad.
-l
Make stdout line buffered. Useful if you want to see the data while capturing it. E.g.,
``tcpdump  -l  |  tee dat'' or ``tcpdump  -l   > dat  &  tail  -f  dat''.
-L
List the known data link types for the interface and exit.
-m
Load SMI MIB module definitions from file module. This option can be used several times to load several MIB modules into tcpdump.
-M
Use secret as a shared secret for validating the digests found in TCP segments with the TCP-MD5 option (RFC 2385), if present.
-n
Don't convert addresses (i.e., host addresses, port numbers, etc.) to names.
-N
Don't print domain name qualification of host names. E.g., if you give this flag then tcpdump will print ``nic'' instead of ``nic.ddn.mil''.
-O
Do not run the packet-matching code optimizer. This is useful only if you suspect a bug in the optimizer.
-p
Don't put the interface into promiscuous mode. Note that the interface might be in promiscuous mode for some other reason; hence, `-p' cannot be used as an abbreviation for `ether host {local-hw-addr} or ether broadcast'.
-q
Quick (quiet?) output. Print less protocol information so output lines are shorter.
-R
Assume ESP/AH packets to be based on old specification (RFC1825 to RFC1829). If specified, tcpdump will not print replay prevention field. Since there is no protocol version field in ESP/AH specification, tcpdump cannot deduce the version of ESP/AH protocol.
-r
Read packets from file (which was created with the -w option). Standard input is used if file is ``-''.
-S
Print absolute, rather than relative, TCP sequence numbers.
-s
Snarf snaplen bytes of data from each packet rather than the default of 68 (with SunOS's NIT, the minimum is actually 96). 68 bytes is adequate for IP, ICMP, TCP and UDP but may truncate protocol information from name server and NFS packets (see below). Packets truncated because of a limited snapshot are indicated in the output with ``[|proto]'', where proto is the name of the protocol level at which the truncation has occurred. Note that taking larger snapshots both increases the amount of time it takes to process packets and, effectively, decreases the amount of packet buffering. This may cause packets to be lost. You should limit snaplen to the smallest number that will capture the protocol information you're interested in. Setting snaplen to 0 means use the required length to catch whole packets.
-T
Force packets selected by "expression" to be interpreted the specified type. Currently known types are aodv (Ad-hoc On-demand Distance Vector protocol), cnfp (Cisco NetFlow protocol), rpc (Remote Procedure Call), rtp (Real-Time Applications protocol), rtcp (Real-Time Applications control protocol), snmp (Simple Network Management Protocol), tftp (Trivial File Transfer Protocol), vat (Visual Audio Tool), and wb (distributed White Board).
-t
Don't print a timestamp on each dump line.
-tt
Print an unformatted timestamp on each dump line.
-ttt
Print a delta (micro-second resolution) between current and previous line on each dump line.
-tttt
Print a timestamp in default format proceeded by date on each dump line.
-ttttt
Print a delta (micro-second resolution) between current and first line on each dump line.
-u
Print undecoded NFS handles.
-U
Make output saved via the -w option ``packet-buffered''; i.e., as each packet is saved, it will be written to the output file, rather than being written only when the output buffer fills.
The -U flag will not be supported if tcpdump was built with an older version of libpcap that lacks the pcap_dump_flush() function.
-v
When parsing and printing, produce (slightly more) verbose output. For example, the time to live, identification, total length and options in an IP packet are printed. Also enables additional packet integrity checks such as verifying the IP and ICMP header checksum.
When writing to a file with the -w option, report, every 10 seconds, the number of packets captured.
-vv
Even more verbose output. For example, additional fields are printed from NFS reply packets, and SMB packets are fully decoded.
-vvv
Even more verbose output. For example, telnet SB ... SE options are printed in full. With -X Telnet options are printed in hex as well.
-w
Write the raw packets to file rather than parsing and printing them out. They can later be printed with the -r option. Standard output is used if file is ``-''.
-W
Used in conjunction with the -C option, this will limit the number of files created to the specified number, and begin overwriting files from the beginning, thus creating a 'rotating' buffer. In addition, it will name the files with enough leading 0s to support the maximum number of files, allowing them to sort correctly.
Used in conjunction with the -G option, this will limit the number of rotated dump files that get created, exiting with status 0 when reaching the limit. If used with -C as well, the behavior will result in cyclical files per timeslice.
-x
When parsing and printing, in addition to printing the headers of each packet, print the data of each packet (minus its link level header) in hex. The smaller of the entire packet or snaplen bytes will be printed. Note that this is the entire link-layer packet, so for link layers that pad (e.g. Ethernet), the padding bytes will also be printed when the higher layer packet is shorter than the required padding.
-xx
When parsing and printing, in addition to printing the headers of each packet, print the data of each packet, including its link level header, in hex.
-X
When parsing and printing, in addition to printing the headers of each packet, print the data of each packet (minus its link level header) in hex and ASCII. This is very handy for analysing new protocols.
-XX
When parsing and printing, in addition to printing the headers of each packet, print the data of each packet, including its link level header, in hex and ASCII.
-y
Set the data link type to use while capturing packets to datalinktype.
-z
Used in conjunction with the -C or -G options, this will make tcpdump run " command file " where file is the savefile being closed after each rotation. For example, specifying -z gzip or -z bzip2 will compress each savefile using gzip or bzip2.
Note that tcpdump will run the command in parallel to the capture, using the lowest priority so that this doesn't disturb the capture process.
And in case you would like to use a command that itself takes flags or different arguments, you can always write a shell script that will take the savefile name as the only argument, make the flags & arguments arrangements and execute the command that you want.
-Z
Drops privileges (if root) and changes user ID to user and the group ID to the primary group of user.
This behavior can also be enabled by default at compile time.
expression
selects which packets will be dumped. If no expression is given, all packets on the net will be dumped. Otherwise, only packets for which expression is `true' will be dumped.

The expression consists of one or more primitives. Primitives usually consist of an id (name or number) preceded by one or more qualifiers. There are three different kinds of qualifier:

type
qualifiers say what kind of thing the id name or number refers to. Possible types are host, net , port and portrange. E.g., `host foo', `net 128.3', `port 20', `portrange 6000-6008'. If there is no type qualifier, host is assumed.
dir
qualifiers specify a particular transfer direction to and/or from id. Possible directions are src, dst, src or dst and src and dst. E.g., `src foo', `dst net 128.3', `src or dst port ftp-data'. If there is no dir qualifier, src or dst is assumed. For some link layers, such as SLIP and the ``cooked'' Linux capture mode used for the ``any'' device and for some other device types, the inbound and outbound qualifiers can be used to specify a desired direction.
proto
qualifiers restrict the match to a particular protocol. Possible protos are: ether, fddi, tr, wlan, ip, ip6, arp, rarp, decnet, tcp and udp. E.g., `ether src foo', `arp net 128.3', `tcp port 21', `udp portrange 7000-7009'. If there is no proto qualifier, all protocols consistent with the type are assumed. E.g., `src foo' means `(ip or arp or rarp) src foo' (except the latter is not legal syntax), `net bar' means `(ip or arp or rarp) net bar' and `port 53' means `(tcp or udp) port 53'.

[`fddi' is actually an alias for `ether'; the parser treats them identically as meaning ``the data link level used on the specified network interface.'' FDDI headers contain Ethernet-like source and destination addresses, and often contain Ethernet-like packet types, so you can filter on these FDDI fields just as with the analogous Ethernet fields. FDDI headers also contain other fields, but you cannot name them explicitly in a filter expression.

Similarly, `tr' and `wlan' are aliases for `ether'; the previous paragraph's statements about FDDI headers also apply to Token Ring and 802.11 wireless LAN headers. For 802.11 headers, the destination address is the DA field and the source address is the SA field; the BSSID, RA, and TA fields aren't tested.]

In addition to the above, there are some special `primitive' keywords that don't follow the pattern: gateway, broadcast, less, greater and arithmetic expressions. All of these are described below.

More complex filter expressions are built up by using the words and, or and not to combine primitives. E.g., `host foo and not port ftp and not port ftp-data'. To save typing, identical qualifier lists can be omitted. E.g., `tcp dst port ftp or ftp-data or domain' is exactly the same as `tcp dst port ftp or tcp dst port ftp-data or tcp dst port domain'.

Allowable primitives are:

dst host host
True if the IPv4/v6 destination field of the packet is host, which may be either an address or a name.
src host host
True if the IPv4/v6 source field of the packet is host.
host host
True if either the IPv4/v6 source or destination of the packet is host.
Any of the above host expressions can be prepended with the keywords, ip, arp, rarp, or ip6 as in:
ip host host
which is equivalent to:
ether proto \ip and host host
If host is a name with multiple IP addresses, each address will be checked for a match.
ether dst ehost
True if the Ethernet destination address is ehost. Ehost may be either a name from /etc/ethers or a number (see ethers(3N) for numeric format).
ether src ehost
True if the Ethernet source address is ehost.
ether host ehost
True if either the Ethernet source or destination address is ehost.
gateway host
True if the packet used host as a gateway. I.e., the Ethernet source or destination address was host but neither the IP source nor the IP destination was host. Host must be a name and must be found both by the machine's host-name-to-IP-address resolution mechanisms (host name file, DNS, NIS, etc.) and by the machine's host-name-to-Ethernet-address resolution mechanism (/etc/ethers, etc.). (An equivalent expression is
ether host ehost and not host host
which can be used with either names or numbers for host / ehost.) This syntax does not work in IPv6-enabled configuration at this moment.
dst net net
True if the IPv4/v6 destination address of the packet has a network number of net. Net may be either a name from the networks database (/etc/networks, etc.) or a network number. An IPv4 network number can be written as a dotted quad (e.g., 192.168.1.0), dotted triple (e.g., 192.168.1), dotted pair (e.g, 172.16), or single number (e.g., 10); the netmask is 255.255.255.255 for a dotted quad (which means that it's really a host match), 255.255.255.0 for a dotted triple, 255.255.0.0 for a dotted pair, or 255.0.0.0 for a single number. An IPv6 network number must be written out fully; the netmask is ff:ff:ff:ff:ff:ff:ff:ff, so IPv6 "network" matches are really always host matches, and a network match requires a netmask length.
src net net
True if the IPv4/v6 source address of the packet has a network number of net.
net net
True if either the IPv4/v6 source or destination address of the packet has a network number of net.
net net mask netmask
True if the IPv4 address matches net with the specific netmask. May be qualified with src or dst. Note that this syntax is not valid for IPv6 net.
net net/len
True if the IPv4/v6 address matches net with a netmask len bits wide. May be qualified with src or dst.
dst port port
True if the packet is ip/tcp, ip/udp, ip6/tcp or ip6/udp and has a destination port value of port. The port can be a number or a name used in /etc/services (see tcp(4P) and udp(4P)). If a name is used, both the port number and protocol are checked. If a number or ambiguous name is used, only the port number is checked (e.g., dst port 513 will print both tcp/login traffic and udp/who traffic, and port domain will print both tcp/domain and udp/domain traffic).
src port port
True if the packet has a source port value of port.
port port
True if either the source or destination port of the packet is port.
dst portrange port1-port2
True if the packet is ip/tcp, ip/udp, ip6/tcp or ip6/udp and has a destination port value between port1 and port2. port1 and port2 are interpreted in the same fashion as the port parameter for port.
src portrange port1-port2
True if the packet has a source port value between port1 and port2.
portrange port1-port2
True if either the source or destination port of the packet is between port1 and port2.
Any of the above port or port range expressions can be prepended with the keywords, tcp or udp, as in:
tcp src port port
which matches only tcp packets whose source port is port.
less length
True if the packet has a length less than or equal to length. This is equivalent to:
len <= length.
greater length
True if the packet has a length greater than or equal to length. This is equivalent to:
len >= length.
ip proto protocol
True if the packet is an IPv4 packet (see ip(4P)) of protocol type protocol. Protocol can be a number or one of the names icmp, icmp6, igmp, igrp, pim, ah, esp, vrrp, udp, or tcp. Note that the identifiers tcp, udp, and icmp are also keywords and must be escaped via backslash (\), which is \\ in the C-shell. Note that this primitive does not chase the protocol header chain.
ip6 proto protocol
True if the packet is an IPv6 packet of protocol type protocol. Note that this primitive does not chase the protocol header chain.
ip6 protochain protocol
True if the packet is IPv6 packet, and contains protocol header with type protocol in its protocol header chain. For example,
ip6 protochain 6
matches any IPv6 packet with TCP protocol header in the protocol header chain. The packet may contain, for example, authentication header, routing header, or hop-by-hop option header, between IPv6 header and TCP header. The BPF code emitted by this primitive is complex and cannot be optimized by BPF optimizer code in tcpdump, so this can be somewhat slow.
ip protochain protocol
Equivalent to ip6 protochain protocol, but this is for IPv4.
ether broadcast
True if the packet is an Ethernet broadcast packet. The ether keyword is optional.
ip broadcast
True if the packet is an IPv4 broadcast packet. It checks for both the all-zeroes and all-ones broadcast conventions, and looks up the subnet mask on the interface on which the capture is being done.
If the subnet mask of the interface on which the capture is being done is not available, either because the interface on which capture is being done has no netmask or because the capture is being done on the Linux "any" interface, which can capture on more than one interface, this check will not work correctly.
ether multicast
True if the packet is an Ethernet multicast packet. The ether keyword is optional. This is shorthand for `ether[0] & 1 != 0'.
ip multicast
True if the packet is an IPv4 multicast packet.
ip6 multicast
True if the packet is an IPv6 multicast packet.
ether proto protocol
True if the packet is of ether type protocol. Protocol can be a number or one of the names ip, ip6, arp, rarp, atalk, aarp, decnet, sca, lat, mopdl, moprc, iso, stp, ipx, or netbeui. Note these identifiers are also keywords and must be escaped via backslash (\).
[In the case of FDDI (e.g., `fddi protocol arp'), Token Ring (e.g., `tr protocol arp'), and IEEE 802.11 wireless LANS (e.g., `wlan protocol arp'), for most of those protocols, the protocol identification comes from the 802.2 Logical Link Control (LLC) header, which is usually layered on top of the FDDI, Token Ring, or 802.11 header.
When filtering for most protocol identifiers on FDDI, Token Ring, or 802.11, tcpdump checks only the protocol ID field of an LLC header in so-called SNAP format with an Organizational Unit Identifier (OUI) of 0x000000, for encapsulated Ethernet; it doesn't check whether the packet is in SNAP format with an OUI of 0x000000. The exceptions are:
iso
tcpdump checks the DSAP (Destination Service Access Point) and SSAP (Source Service Access Point) fields of the LLC header;
stp and netbeui
tcpdump checks the DSAP of the LLC header;
atalk
tcpdump checks for a SNAP-format packet with an OUI of 0x080007 and the AppleTalk etype.
In the case of Ethernet, tcpdump checks the Ethernet type field for most of those protocols. The exceptions are:
iso, stp, and netbeui
tcpdump checks for an 802.3 frame and then checks the LLC header as it does for FDDI, Token Ring, and 802.11;
atalk
tcpdump checks both for the AppleTalk etype in an Ethernet frame and for a SNAP-format packet as it does for FDDI, Token Ring, and 802.11;
aarp
tcpdump checks for the AppleTalk ARP etype in either an Ethernet frame or an 802.2 SNAP frame with an OUI of 0x000000;
ipx
tcpdump checks for the IPX etype in an Ethernet frame, the IPX DSAP in the LLC header, the 802.3-with-no-LLC-header encapsulation of IPX, and the IPX etype in a SNAP frame.
decnet src host
True if the DECNET source address is host, which may be an address of the form ``10.123'', or a DECNET host name. [DECNET host name support is only available on ULTRIX systems that are configured to run DECNET.]
decnet dst host
True if the DECNET destination address is host.
decnet host host
True if either the DECNET source or destination address is host.
ifname interface
True if the packet was logged as coming from the specified interface (applies only to packets logged by OpenBSD's pf(4)).
on interface
Synonymous with the ifname modifier.
rnr num
True if the packet was logged as matching the specified PF rule number (applies only to packets logged by OpenBSD's pf(4)).
rulenum num
Synonomous with the rnr modifier.
reason code
True if the packet was logged with the specified PF reason code. The known codes are: match, bad-offset, fragment, short, normalize, and memory (applies only to packets logged by OpenBSD's pf(4)).
rset name
True if the packet was logged as matching the specified PF ruleset name of an anchored ruleset (applies only to packets logged by pf(4)).
ruleset name
Synonomous with the rset modifier.
srnr num
True if the packet was logged as matching the specified PF rule number of an anchored ruleset (applies only to packets logged by pf(4)).
subrulenum num
Synonomous with the srnr modifier.
action act
True if PF took the specified action when the packet was logged. Known actions are: pass and block (applies only to packets logged by OpenBSD's pf(4)).
ip, ip6, arp, rarp, atalk, aarp, decnet, iso, stp, ipx, netbeui
Abbreviations for:
ether proto p
where p is one of the above protocols.
lat, moprc, mopdl
Abbreviations for:
ether proto p
where p is one of the above protocols. Note that tcpdump does not currently know how to parse these protocols.
type wlan_type
True if the IEEE 802.11 frame type matches the specified wlan_type. Valid wlan_types are: mgt, ctl and data.
type wlan_type subtype wlan_subtype
True if the IEEE 802.11 frame type matches the specified wlan_type and frame subtype matches the specified wlan_subtype.
If the specified wlan_type is mgt, then valid wlan_subtypes are: assoc-req, assoc-resp, reassoc-req, reassoc-resp, probe-req, probe-resp, beacon, atim, disassoc, auth and deauth.
If the specified wlan_type is ctl, then valid wlan_subtypes are: ps-poll, rts, cts, ack, cf-end and cf-end-ack.
If the specified wlan_type is data, then valid wlan_subtypes are: data, data-cf-ack, data-cf-poll, data-cf-ack-poll, null, cf-ack, cf-poll, cf-ack-poll, qos-data, qos-data-cf-ack, qos-data-cf-poll, qos-data-cf-ack-poll, qos, qos-cf-poll and qos-cf-ack-poll.
subtype wlan_subtype
True if the IEEE 802.11 frame subtype matches the specified wlan_subtype and frame has the type to which the specified wlan_subtype belongs.
vlan [vlan_id]
True if the packet is an IEEE 802.1Q VLAN packet. If [vlan_id] is specified, only true if the packet has the specified vlan_id. Note that the first vlan keyword encountered in expression changes the decoding offsets for the remainder of expression on the assumption that the packet is a VLAN packet. The vlan [vlan_id] expression may be used more than once, to filter on VLAN hierarchies. Each use of that expression increments the filter offsets by 4.
For example:
vlan 100 && vlan 200
filters on VLAN 200 encapsulated within VLAN 100, and
vlan && vlan 300 && ip
filters IPv4 protocols encapsulated in VLAN 300 encapsulated within any higher order VLAN.
mpls [label_num]
True if the packet is an MPLS packet. If [label_num] is specified, only true is the packet has the specified label_num. Note that the first mpls keyword encountered in expression changes the decoding offsets for the remainder of expression on the assumption that the packet is a MPLS-encapsulated IP packet. The mpls [label_num] expression may be used more than once, to filter on MPLS hierarchies. Each use of that expression increments the filter offsets by 4.
For example:
mpls 100000 && mpls 1024
filters packets with an outer label of 100000 and an inner label of 1024, and
mpls && mpls 1024 && host 192.9.200.1
filters packets to or from 192.9.200.1 with an inner label of 1024 and any outer label.
pppoed
True if the packet is a PPP-over-Ethernet Discovery packet (Ethernet type 0x8863).
pppoes
True if the packet is a PPP-over-Ethernet Session packet (Ethernet type 0x8864). Note that the first pppoes keyword encountered in expression changes the decoding offsets for the remainder of expression on the assumption that the packet is a PPPoE session packet.
For example:
pppoes && ip
filters IPv4 protocols encapsulated in PPPoE.
tcp, udp, icmp
Abbreviations for:
ip proto p or ip6 proto p
where p is one of the above protocols.
iso proto protocol
True if the packet is an OSI packet of protocol type protocol. Protocol can be a number or one of the names clnp, esis, or isis.
clnp, esis, isis
Abbreviations for:
iso proto p
where p is one of the above protocols.
l1, l2, iih, lsp, snp, csnp, psnp
Abbreviations for IS-IS PDU types.
vpi n
True if the packet is an ATM packet, for SunATM on Solaris, with a virtual path identifier of n.
vci n
True if the packet is an ATM packet, for SunATM on Solaris, with a virtual channel identifier of n.
lane
True if the packet is an ATM packet, for SunATM on Solaris, and is an ATM LANE packet. Note that the first lane keyword encountered in expression changes the tests done in the remainder of expression on the assumption that the packet is either a LANE emulated Ethernet packet or a LANE LE Control packet. If lane isn't specified, the tests are done under the assumption that the packet is an LLC-encapsulated packet.
llc
True if the packet is an ATM packet, for SunATM on Solaris, and is an LLC-encapsulated packet.
oamf4s
True if the packet is an ATM packet, for SunATM on Solaris, and is a segment OAM F4 flow cell (VPI=0 & VCI=3).
oamf4e
True if the packet is an ATM packet, for SunATM on Solaris, and is an end-to-end OAM F4 flow cell (VPI=0 & VCI=4).
oamf4
True if the packet is an ATM packet, for SunATM on Solaris, and is a segment or end-to-end OAM F4 flow cell (VPI=0 & (VCI=3 | VCI=4)).
oam
True if the packet is an ATM packet, for SunATM on Solaris, and is a segment or end-to-end OAM F4 flow cell (VPI=0 & (VCI=3 | VCI=4)).
metac
True if the packet is an ATM packet, for SunATM on Solaris, and is on a meta signaling circuit (VPI=0 & VCI=1).
bcc
True if the packet is an ATM packet, for SunATM on Solaris, and is on a broadcast signaling circuit (VPI=0 & VCI=2).
sc
True if the packet is an ATM packet, for SunATM on Solaris, and is on a signaling circuit (VPI=0 & VCI=5).
ilmic
True if the packet is an ATM packet, for SunATM on Solaris, and is on an ILMI circuit (VPI=0 & VCI=16).
connectmsg
True if the packet is an ATM packet, for SunATM on Solaris, and is on a signaling circuit and is a Q.2931 Setup, Call Proceeding, Connect, Connect Ack, Release, or Release Done message.
metaconnect
True if the packet is an ATM packet, for SunATM on Solaris, and is on a meta signaling circuit and is a Q.2931 Setup, Call Proceeding, Connect, Release, or Release Done message.
expr relop expr
True if the relation holds, where relop is one of >, <, >=, <=, =, !=, and expr is an arithmetic expression composed of integer constants (expressed in standard C syntax), the normal binary operators [+, -, *, /, &, |, <<, >>], a length operator, and special packet data accessors. Note that all comparisons are unsigned, so that, for example, 0x80000000 and 0xffffffff are > 0. To access data inside the packet, use the following syntax:
proto [ expr : size ]
Proto is one of ether, fddi, tr, wlan, ppp, slip, link, ip, arp, rarp, tcp, udp, icmp, ip6 or radio, and indicates the protocol layer for the index operation. (ether, fddi, wlan, tr, ppp, slip and link all refer to the link layer. radio refers to the "radio header" added to some 802.11 captures.) Note that tcp, udp and other upper-layer protocol types only apply to IPv4, not IPv6 (this will be fixed in the future). The byte offset, relative to the indicated protocol layer, is given by expr. Size is optional and indicates the number of bytes in the field of interest; it can be either one, two, or four, and defaults to one. The length operator, indicated by the keyword len, gives the length of the packet.

For example, `ether[0] & 1 != 0' catches all multicast traffic. The expression `ip[0] & 0xf != 5' catches all IPv4 packets with options. The expression `ip[6:2] & 0x1fff = 0' catches only unfragmented IPv4 datagrams and frag zero of fragmented IPv4 datagrams. This check is implicitly applied to the tcp and udp index operations. For instance, tcp[0] always means the first byte of the TCP header, and never means the first byte of an intervening fragment.

Some offsets and field values may be expressed as names rather than as numeric values. The following protocol header field offsets are available: icmptype (ICMP type field), icmpcode (ICMP code field), and tcpflags (TCP flags field).

The following ICMP type field values are available: icmp-echoreply, icmp-unreach, icmp-sourcequench, icmp-redirect, icmp-echo, icmp-routeradvert, icmp-routersolicit, icmp-timxceed, icmp-paramprob, icmp-tstamp, icmp-tstampreply, icmp-ireq, icmp-ireqreply, icmp-maskreq, icmp-maskreply.

The following TCP flags field values are available: tcp-fin, tcp-syn, tcp-rst, tcp-push, tcp-ack, tcp-urg.

Primitives may be combined using:

A parenthesized group of primitives and operators (parentheses are special to the Shell and must be escaped).
Negation (`!' or `not').
Concatenation (`&&' or `and').
Alternation (`||' or `or').

Negation has highest precedence. Alternation and concatenation have equal precedence and associate left to right. Note that explicit and tokens, not juxtaposition, are now required for concatenation.

If an identifier is given without a keyword, the most recent keyword is assumed. For example,

not host vs and ace
is short for
not host vs and host ace
which should not be confused with
not ( host vs or ace )

Expression arguments can be passed to tcpdump as either a single argument or as multiple arguments, whichever is more convenient. Generally, if the expression contains Shell metacharacters, it is easier to pass it as a single, quoted argument. Multiple arguments are concatenated with spaces before being parsed.

 

EXAMPLES

To print all packets arriving at or departing from sundown:

tcpdump host sundown

To print traffic between helios and either hot or ace:

tcpdump host helios and \( hot or ace \)

To print all IP packets between ace and any host except helios:

tcpdump ip host ace and not helios

To print all traffic between local hosts and hosts at Berkeley:

tcpdump net ucb-ether

To print all ftp traffic through internet gateway snup: (note that the expression is quoted to prevent the shell from (mis-)interpreting the parentheses):

tcpdump 'gateway snup and (port ftp or ftp-data)'

To print traffic neither sourced from nor destined for local hosts (if you gateway to one other net, this stuff should never make it onto your local net).

tcpdump ip and not net localnet

To print the start and end packets (the SYN and FIN packets) of each TCP conversation that involves a non-local host.

tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net localnet'

To print all IPv4 HTTP packets to and from port 80, i.e. print only packets that contain data, not, for example, SYN and FIN packets and ACK-only packets. (IPv6 is left as an exercise for the reader.)

tcpdump 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'

To print IP packets longer than 576 bytes sent through gateway snup:

tcpdump 'gateway snup and ip[2:2] > 576'

To print IP broadcast or multicast packets that were not sent via Ethernet broadcast or multicast:

tcpdump 'ether[0] & 1 = 0 and ip[16] >= 224'

To print all ICMP packets that are not echo requests/replies (i.e., not ping packets):

tcpdump 'icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply'
 

OUTPUT FORMAT

The output of tcpdump is protocol dependent. The following gives a brief description and examples of most of the formats.

Link Level Headers

If the '-e' option is given, the link level header is printed out. On Ethernets, the source and destination addresses, protocol, and packet length are printed.

On FDDI networks, the '-e' option causes tcpdump to print the `frame control' field, the source and destination addresses, and the packet length. (The `frame control' field governs the interpretation of the rest of the packet. Normal packets (such as those containing IP datagrams) are `async' packets, with a priority value between 0 and 7; for example, `async4'. Such packets are assumed to contain an 802.2 Logical Link Control (LLC) packet; the LLC header is printed if it is not an ISO datagram or a so-called SNAP packet.

On Token Ring networks, the '-e' option causes tcpdump to print the `access control' and `frame control' fields, the source and destination addresses, and the packet length. As on FDDI networks, packets are assumed to contain an LLC packet. Regardless of whether the '-e' option is specified or not, the source routing information is printed for source-routed packets.

On 802.11 networks, the '-e' option causes tcpdump to print the `frame control' fields, all of the addresses in the 802.11 header, and the packet length. As on FDDI networks, packets are assumed to contain an LLC packet.

(N.B.: The following description assumes familiarity with the SLIP compression algorithm described in RFC-1144.)

On SLIP links, a direction indicator (``I'' for inbound, ``O'' for outbound), packet type, and compression information are printed out. The packet type is printed first. The three types are ip, utcp, and ctcp. No further link information is printed for ip packets. For TCP packets, the connection identifier is printed following the type. If the packet is compressed, its encoded header is printed out. The special cases are printed out as *S+n and *SA+n, where n is the amount by which the sequence number (or sequence number and ack) has changed. If it is not a special case, zero or more changes are printed. A change is indicated by U (urgent pointer), W (window), A (ack), S (sequence number), and I (packet ID), followed by a delta (+n or -n), or a new value (=n). Finally, the amount of data in the packet and compressed header length are printed.

For example, the following line shows an outbound compressed TCP packet, with an implicit connection identifier; the ack has changed by 6, the sequence number by 49, and the packet ID by 6; there are 3 bytes of data and 6 bytes of compressed header:

O ctcp * A+6 S+49 I+6 3 (6)

ARP/RARP Packets

Arp/rarp output shows the type of request and its arguments. The format is intended to be self explanatory. Here is a short sample taken from the start of an `rlogin' from host rtsg to host csam:

arp who-has csam tell rtsg
arp reply csam is-at CSAM

The first line says that rtsg sent an arp packet asking for the Ethernet address of internet host csam. Csam replies with its Ethernet address (in this example, Ethernet addresses are in caps and internet addresses in lower case).

This would look less redundant if we had done tcpdump -n:

arp who-has 128.3.254.6 tell 128.3.254.68
arp reply 128.3.254.6 is-at 02:07:01:00:01:c4

If we had done tcpdump -e, the fact that the first packet is broadcast and the second is point-to-point would be visible:

RTSG Broadcast 0806  64: arp who-has csam tell rtsg
CSAM RTSG 0806  64: arp reply csam is-at CSAM

For the first packet this says the Ethernet source address is RTSG, the destination is the Ethernet broadcast address, the type field contained hex 0806 (type ETHER_ARP) and the total length was 64 bytes.

TCP Packets

(N.B.:The following description assumes familiarity with the TCP protocol described in RFC-793. If you are not familiar with the protocol, neither this description nor tcpdump will be of much use to you.)

The general format of a tcp protocol line is:

src > dst: flags data-seqno ack window urgent options

Src and dst are the source and destination IP addresses and ports. Flags are some combination of S (SYN), F (FIN), P (PUSH), R (RST), W (ECN CWR) or E (ECN-Echo), or a single `.' (no flags). Data-seqno describes the portion of sequence space covered by the data in this packet (see example below). Ack is sequence number of the next data expected the other direction on this connection. Window is the number of bytes of receive buffer space available the other direction on this connection. Urg indicates there is `urgent' data in the packet. Options are tcp options enclosed in angle brackets (e.g., <mss 1024>).

Src, dst and flags are always present. The other fields depend on the contents of the packet's tcp protocol header and are output only if appropriate.

Here is the opening portion of an rlogin from host rtsg to host csam.

rtsg.1023 > csam.login: S 768512:768512(0) win 4096 <mss 1024>
csam.login > rtsg.1023: S 947648:947648(0) ack 768513 win 4096 <mss 1024>
rtsg.1023 > csam.login: . ack 1 win 4096
rtsg.1023 > csam.login: P 1:2(1) ack 1 win 4096
csam.login > rtsg.1023: . ack 2 win 4096
rtsg.1023 > csam.login: P 2:21(19) ack 1 win 4096
csam.login > rtsg.1023: P 1:2(1) ack 21 win 4077
csam.login > rtsg.1023: P 2:3(1) ack 21 win 4077 urg 1
csam.login > rtsg.1023: P 3:4(1) ack 21 win 4077 urg 1

The first line says that tcp port 1023 on rtsg sent a packet to port login on csam. The S indicates that the SYN flag was set. The packet sequence number was 768512 and it contained no data. (The notation is `first:last(nbytes)' which means `sequence numbers first up to but not including last which is nbytes bytes of user data'.) There was no piggy-backed ack, the available receive window was 4096 bytes and there was a max-segment-size option requesting an mss of 1024 bytes.

Csam replies with a similar packet except it includes a piggy-backed ack for rtsg's SYN. Rtsg then acks csam's SYN. The `.' means no flags were set. The packet contained no data so there is no data sequence number. Note that the ack sequence number is a small integer (1). The first time tcpdump sees a tcp `conversation', it prints the sequence number from the packet. On subsequent packets of the conversation, the difference between the current packet's sequence number and this initial sequence number is printed. This means that sequence numbers after the first can be interpreted as relative byte positions in the conversation's data stream (with the first data byte each direction being `1'). `-S' will override this feature, causing the original sequence numbers to be output.

On the 6th line, rtsg sends csam 19 bytes of data (bytes 2 through 20 in the rtsg -> csam side of the conversation). The PUSH flag is set in the packet. On the 7th line, csam says it's received data sent by rtsg up to but not including byte 21. Most of this data is apparently sitting in the socket buffer since csam's receive window has gotten 19 bytes smaller. Csam also sends one byte of data to rtsg in this packet. On the 8th and 9th lines, csam sends two bytes of urgent, pushed data to rtsg.

If the snapshot was small enough that tcpdump didn't capture the full TCP header, it interprets as much of the header as it can and then reports ``[|tcp]'' to indicate the remainder could not be interpreted. If the header contains a bogus option (one with a length that's either too small or beyond the end of the header), tcpdump reports it as ``[bad opt]'' and does not interpret any further options (since it's impossible to tell where they start). If the header length indicates options are present but the IP datagram length is not long enough for the options to actually be there, tcpdump reports it as ``[bad hdr length]''.

Capturing TCP packets with particular flag combinations (SYN-ACK, URG-ACK, etc.)

There are 8 bits in the control bits section of the TCP header:

CWR | ECE | URG | ACK | PSH | RST | SYN | FIN

Let's assume that we want to watch packets used in establishing a TCP connection. Recall that TCP uses a 3-way handshake protocol when it initializes a new connection; the connection sequence with regard to the TCP control bits is

1) Caller sends SYN
2) Recipient responds with SYN, ACK
3) Caller sends ACK

Now we're interested in capturing packets that have only the SYN bit set (Step 1). Note that we don't want packets from step 2 (SYN-ACK), just a plain initial SYN. What we need is a correct filter expression for tcpdump.

Recall the structure of a TCP header without options:

 0                            15                              31
-----------------------------------------------------------------
|          source port          |       destination port        |
-----------------------------------------------------------------
|                        sequence number                        |
-----------------------------------------------------------------
|                     acknowledgment number                     |
-----------------------------------------------------------------
|  HL   | rsvd  |C|E|U|A|P|R|S|F|        window size            |
-----------------------------------------------------------------
|         TCP checksum          |       urgent pointer          |
-----------------------------------------------------------------

A TCP header usually holds 20 octets of data, unless options are present. The first line of the graph contains octets 0 - 3, the second line shows octets 4 - 7 etc.

Starting to count with 0, the relevant TCP control bits are contained in octet 13:

 0             7|             15|             23|             31
----------------|---------------|---------------|----------------
|  HL   | rsvd  |C|E|U|A|P|R|S|F|        window size            |
----------------|---------------|---------------|----------------
|               |  13th octet   |               |               |

Let's have a closer look at octet no. 13:

                |               |
                |---------------|
                |C|E|U|A|P|R|S|F|
                |---------------|
                |7   5   3     0|

These are the TCP control bits we are interested in. We have numbered the bits in this octet from 0 to 7, right to left, so the PSH bit is bit number 3, while the URG bit is number 5.

Recall that we want to capture packets with only SYN set. Let's see what happens to octet 13 if a TCP datagram arrives with the SYN bit set in its header:

                |C|E|U|A|P|R|S|F|
                |---------------|
                |0 0 0 0 0 0 1 0|
                |---------------|
                |7 6 5 4 3 2 1 0|

Looking at the control bits section we see that only bit number 1 (SYN) is set.

Assuming that octet number 13 is an 8-bit unsigned integer in network byte order, the binary value of this octet is

00000010

and its decimal representation is

   7     6     5     4     3     2     1     0
0*2 + 0*2 + 0*2 + 0*2 + 0*2 + 0*2 + 1*2 + 0*2  =  2

We're almost done, because now we know that if only SYN is set, the value of the 13th octet in the TCP header, when interpreted as a 8-bit unsigned integer in network byte order, must be exactly 2.

This relationship can be expressed as

tcp[13] == 2

We can use this expression as the filter for tcpdump in order to watch packets which have only SYN set:

tcpdump -i xl0 tcp[13] == 2

The expression says "let the 13th octet of a TCP datagram have the decimal value 2", which is exactly what we want.

Now, let's assume that we need to capture SYN packets, but we don't care if ACK or any other TCP control bit is set at the same time. Let's see what happens to octet 13 when a TCP datagram with SYN-ACK set arrives:

     |C|E|U|A|P|R|S|F|
     |---------------|
     |0 0 0 1 0 0 1 0|
     |---------------|
     |7 6 5 4 3 2 1 0|

Now bits 1 and 4 are set in the 13th octet. The binary value of octet 13 is


     00010010

which translates to decimal

   7     6     5     4     3     2     1     0
0*2 + 0*2 + 0*2 + 1*2 + 0*2 + 0*2 + 1*2 + 0*2   = 18

Now we can't just use 'tcp[13] == 18' in the tcpdump filter expression, because that would select only those packets that have SYN-ACK set, but not those with only SYN set. Remember that we don't care if ACK or any other control bit is set as long as SYN is set.

In order to achieve our goal, we need to logically AND the binary value of octet 13 with some other value to preserve the SYN bit. We know that we want SYN to be set in any case, so we'll logically AND the value in the 13th octet with the binary value of a SYN:

          00010010 SYN-ACK              00000010 SYN
     AND  00000010 (we want SYN)   AND  00000010 (we want SYN)
          --------                      --------
     =    00000010                 =    00000010

We see that this AND operation delivers the same result regardless whether ACK or another TCP control bit is set. The decimal representation of the AND value as well as the result of this operation is 2 (binary 00000010), so we know that for packets with SYN set the following relation must hold true:

( ( value of octet 13 ) AND ( 2 ) ) == ( 2 )

This points us to the tcpdump filter expression


     tcpdump -i xl0 'tcp[13] & 2 == 2'

Note that you should use single quotes or a backslash in the expression to hide the AND ('&') special character from the shell.

UDP Packets

UDP format is illustrated by this rwho packet:

actinide.who > broadcast.who: udp 84

This says that port who on host actinide sent a udp datagram to port who on host broadcast, the Internet broadcast address. The packet contained 84 bytes of user data.

Some UDP services are recognized (from the source or destination port number) and the higher level protocol information printed. In particular, Domain Name service requests (RFC-1034/1035) and Sun RPC calls (RFC-1050) to NFS.

UDP Name Server Requests

(N.B.:The following description assumes familiarity with the Domain Service protocol described in RFC-1035. If you are not familiar with the protocol, the following description will appear to be written in greek.)

Name server requests are formatted as

src > dst: id op? flags qtype qclass name (len)

h2opolo.1538 > helios.domain: 3+ A? ucbvax.berkeley.edu. (37)

Host h2opolo asked the domain server on helios for an address record (qtype=A) associated with the name ucbvax.berkeley.edu. The query id was `3'. The `+' indicates the recursion desired flag was set. The query length was 37 bytes, not including the UDP and IP protocol headers. The query operation was the normal one, Query, so the op field was omitted. If the op had been anything else, it would have been printed between the `3' and the `+'. Similarly, the qclass was the normal one, C_IN, and omitted. Any other qclass would have been printed immediately after the `A'.

A few anomalies are checked and may result in extra fields enclosed in square brackets: If a query contains an answer, authority records or additional records section, ancount, nscount, or arcount are printed as `[na]', `[nn]' or `[nau]' where n is the appropriate count. If any of the response bits are set (AA, RA or rcode) or any of the `must be zero' bits are set in bytes two and three, `[b2&3=x]' is printed, where x is the hex value of header bytes two and three.

UDP Name Server Responses

Name server responses are formatted as

src > dst:  id op rcode flags a/n/au type class data (len)

helios.domain > h2opolo.1538: 3 3/3/7 A 128.32.137.3 (273)
helios.domain > h2opolo.1537: 2 NXDomain* 0/1/0 (97)

In the first example, helios responds to query id 3 from h2opolo with 3 answer records, 3 name server records and 7 additional records. The first answer record is type A (address) and its data is internet address 128.32.137.3. The total size of the response was 273 bytes, excluding UDP and IP headers. The op (Query) and response code (NoError) were omitted, as was the class (C_IN) of the A record.

In the second example, helios responds to query 2 with a response code of non-existent domain (NXDomain) with no answers, one name server and no authority records. The `*' indicates that the authoritative answer bit was set. Since there were no answers, no type, class or data were printed.

Other flag characters that might appear are `-' (recursion available, RA, not set) and `|' (truncated message, TC, set). If the `question' section doesn't contain exactly one entry, `[nq]' is printed.

Note that name server requests and responses tend to be large and the default snaplen of 68 bytes may not capture enough of the packet to print. Use the -s flag to increase the snaplen if you need to seriously investigate name server traffic. `-s 128' has worked well for me.

SMB/CIFS decoding

tcpdump now includes fairly extensive SMB/CIFS/NBT decoding for data on UDP/137, UDP/138 and TCP/139. Some primitive decoding of IPX and NetBEUI SMB data is also done.

By default a fairly minimal decode is done, with a much more detailed decode done if -v is used. Be warned that with -v a single SMB packet may take up a page or more, so only use -v if you really want all the gory details.

For information on SMB packet formats and what all te fields mean see www.cifs.org or the pub/samba/specs/ directory on your favorite samba.org mirror site. The SMB patches were written by Andrew Tridgell (tridge@samba.org).

NFS Requests and Replies

Sun NFS (Network File System) requests and replies are printed as:

src.xid > dst.nfs: len op args
src.nfs > dst.xid: reply stat len op results


sushi.6709 > wrl.nfs: 112 readlink fh 21,24/10.73165
wrl.nfs > sushi.6709: reply ok 40 readlink "../var"
sushi.201b > wrl.nfs:
        144 lookup fh 9,74/4096.6878 "xcolors"
wrl.nfs > sushi.201b:
        reply ok 128 lookup fh 9,74/4134.3150


In the first line, host sushi sends a transaction with id 6709 to wrl (note that the number following the src host is a transaction id, not the source port). The request was 112 bytes, excluding the UDP and IP headers. The operation was a readlink (read symbolic link) on file handle (fh) 21,24/10.731657119. (If one is lucky, as in this case, the file handle can be interpreted as a major,minor device number pair, followed by the inode number and generation number.) Wrl replies `ok' with the contents of the link.

In the third line, sushi asks wrl to lookup the name `xcolors' in directory file 9,74/4096.6878. Note that the data printed depends on the operation type. The format is intended to be self explanatory if read in conjunction with an NFS protocol spec.

If the -v (verbose) flag is given, additional information is printed. For example:


sushi.1372a > wrl.nfs:
        148 read fh 21,11/12.195 8192 bytes @ 24576
wrl.nfs > sushi.1372a:
        reply ok 1472 read REG 100664 ids 417/0 sz 29388


(-v also prints the IP header TTL, ID, length, and fragmentation fields, which have been omitted from this example.) In the first line, sushi asks wrl to read 8192 bytes from file 21,11/12.195, at byte offset 24576. Wrl replies `ok'; the packet shown on the second line is the first fragment of the reply, and hence is only 1472 bytes long (the other bytes will follow in subsequent fragments, but these fragments do not have NFS or even UDP headers and so might not be printed, depending on the filter expression used). Because the -v flag is given, some of the file attributes (which are returned in addition to the file data) are printed: the file type (``REG'', for regular file), the file mode (in octal), the uid and gid, and the file size.

If the -v flag is given more than once, even more details are printed.

Note that NFS requests are very large and much of the detail won't be printed unless snaplen is increased. Try using `-s 192' to watch NFS traffic.

NFS reply packets do not explicitly identify the RPC operation. Instead, tcpdump keeps track of ``recent'' requests, and matches them to the replies using the transaction ID. If a reply does not closely follow the corresponding request, it might not be parsable.

AFS Requests and Replies

Transarc AFS (Andrew File System) requests and replies are printed as:

src.sport > dst.dport: rx packet-type
src.sport > dst.dport: rx packet-type service call call-name args
src.sport > dst.dport: rx packet-type service reply call-name args


elvis.7001 > pike.afsfs:
        rx data fs call rename old fid 536876964/1/1 ".newsrc.new"
        new fid 536876964/1/1 ".newsrc"
pike.afsfs > elvis.7001: rx data fs reply rename


In the first line, host elvis sends a RX packet to pike. This was a RX data packet to the fs (fileserver) service, and is the start of an RPC call. The RPC call was a rename, with the old directory file id of 536876964/1/1 and an old filename of `.newsrc.new', and a new directory file id of 536876964/1/1 and a new filename of `.newsrc'. The host pike responds with a RPC reply to the rename call (which was successful, because it was a data packet and not an abort packet).

In general, all AFS RPCs are decoded at least by RPC call name. Most AFS RPCs have at least some of the arguments decoded (generally only the `interesting' arguments, for some definition of interesting).

The format is intended to be self-describing, but it will probably not be useful to people who are not familiar with the workings of AFS and RX.

If the -v (verbose) flag is given twice, acknowledgement packets and additional header information is printed, such as the the RX call ID, call number, sequence number, serial number, and the RX packet flags.

If the -v flag is given twice, additional information is printed, such as the the RX call ID, serial number, and the RX packet flags. The MTU negotiation information is also printed from RX ack packets.

If the -v flag is given three times, the security index and service id are printed.

Error codes are printed for abort packets, with the exception of Ubik beacon packets (because abort packets are used to signify a yes vote for the Ubik protocol).

Note that AFS requests are very large and many of the arguments won't be printed unless snaplen is increased. Try using `-s 256' to watch AFS traffic.

AFS reply packets do not explicitly identify the RPC operation. Instead, tcpdump keeps track of ``recent'' requests, and matches them to the replies using the call number and service ID. If a reply does not closely follow the corresponding request, it might not be parsable.

KIP AppleTalk (DDP in UDP)

AppleTalk DDP packets encapsulated in UDP datagrams are de-encapsulated and dumped as DDP packets (i.e., all the UDP header information is discarded). The file /etc/atalk.names is used to translate AppleTalk net and node numbers to names. Lines in this file have the form

number  name

1.254           ether
16.1            icsd-net
1.254.110       ace

The first two lines give the names of AppleTalk networks. The third line gives the name of a particular host (a host is distinguished from a net by the 3rd octet in the number - a net number must have two octets and a host number must have three octets.) The number and name should be separated by whitespace (blanks or tabs). The /etc/atalk.names file may contain blank lines or comment lines (lines starting with a `#').

AppleTalk addresses are printed in the form

net.host.port

144.1.209.2 > icsd-net.112.220
office.2 > icsd-net.112.220
jssmag.149.235 > icsd-net.2

(If the /etc/atalk.names doesn't exist or doesn't contain an entry for some AppleTalk host/net number, addresses are printed in numeric form.) In the first example, NBP (DDP port 2) on net 144.1 node 209 is sending to whatever is listening on port 220 of net icsd node 112. The second line is the same except the full name of the source node is known (`office'). The third line is a send from port 235 on net jssmag node 149 to broadcast on the icsd-net NBP port (note that the broadcast address (255) is indicated by a net name with no host number - for this reason it's a good idea to keep node names and net names distinct in /etc/atalk.names).

NBP (name binding protocol) and ATP (AppleTalk transaction protocol) packets have their contents interpreted. Other protocols just dump the protocol name (or number if no name is registered for the protocol) and packet size.

NBP packets are formatted like the following examples:

icsd-net.112.220 > jssmag.2: nbp-lkup 190: "=:LaserWriter@*"
jssmag.209.2 > icsd-net.112.220: nbp-reply 190: "RM1140:LaserWriter@*" 250
techpit.2 > icsd-net.112.220: nbp-reply 190: "techpit:LaserWriter@*" 186

The first line is a name lookup request for laserwriters sent by net icsd host 112 and broadcast on net jssmag. The nbp id for the lookup is 190. The second line shows a reply for this request (note that it has the same id) from host jssmag.209 saying that it has a laserwriter resource named "RM1140" registered on port 250. The third line is another reply to the same request saying host techpit has laserwriter "techpit" registered on port 186.

ATP packet formatting is demonstrated by the following example:

jssmag.209.165 > helios.132: atp-req  12266<0-7> 0xae030001
helios.132 > jssmag.209.165: atp-resp 12266:0 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp 12266:1 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp 12266:2 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp 12266:4 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp 12266:6 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp*12266:7 (512) 0xae040000
jssmag.209.165 > helios.132: atp-req  12266<3,5> 0xae030001
helios.132 > jssmag.209.165: atp-resp 12266:3 (512) 0xae040000
helios.132 > jssmag.209.165: atp-resp 12266:5 (512) 0xae040000
jssmag.209.165 > helios.132: atp-rel  12266<0-7> 0xae030001
jssmag.209.133 > helios.132: atp-req* 12267<0-7> 0xae030002

Jssmag.209 initiates transaction id 12266 with host helios by requesting up to 8 packets (the `<0-7>'). The hex number at the end of the line is the value of the `userdata' field in the request.

Helios responds with 8 512-byte packets. The `:digit' following the transaction id gives the packet sequence number in the transaction and the number in parens is the amount of data in the packet, excluding the atp header. The `*' on packet 7 indicates that the EOM bit was set.

Jssmag.209 then requests that packets 3 & 5 be retransmitted. Helios resends them then jssmag.209 releases the transaction. Finally, jssmag.209 initiates the next request. The `*' on the request indicates that XO (`exactly once') was not set.

IP Fragmentation

Fragmented Internet datagrams are printed as

(frag id:size@offset+)
(frag id:size@offset)

(The first form indicates there are more fragments. The second indicates this is the last fragment.)

Id is the fragment id. Size is the fragment size (in bytes) excluding the IP header. Offset is this fragment's offset (in bytes) in the original datagram.

The fragment information is output for each fragment. The first fragment contains the higher level protocol header and the frag info is printed after the protocol info. Fragments after the first contain no higher level protocol header and the frag info is printed after the source and destination addresses. For example, here is part of an ftp from arizona.edu to lbl-rtsg.arpa over a CSNET connection that doesn't appear to handle 576 byte datagrams:

arizona.ftp-data > rtsg.1170: . 1024:1332(308) ack 1 win 4096 (frag 595a:328@0+)
arizona > rtsg: (frag 595a:204@328)
rtsg.1170 > arizona.ftp-data: . ack 1536 win 2560

There are a couple of things to note here: First, addresses in the 2nd line don't include port numbers. This is because the TCP protocol information is all in the first fragment and we have no idea what the port or sequence numbers are when we print the later fragments. Second, the tcp sequence information in the first line is printed as if there were 308 bytes of user data when, in fact, there are 512 bytes (308 in the first frag and 204 in the second). If you are looking for holes in the sequence space or trying to match up acks with packets, this can fool you.

A packet with the IP don't fragment flag is marked with a trailing (DF).

Timestamps

By default, all output lines are preceded by a timestamp. The timestamp is the current clock time in the form

hh:mm:ss.frac
and is as accurate as the kernel's clock. The timestamp reflects the time the kernel first saw the packet. No attempt is made to account for the time lag between when the Ethernet interface removed the packet from the wire and when the kernel serviced the `new packet' interrupt.  

SEE ALSO

stty(1), pcap(3), bpf(4), nit(4P), pfconfig(8)  

AUTHORS

The original authors are:

Van Jacobson, Craig Leres and Steven McCanne, all of the Lawrence Berkeley National Laboratory, University of California, Berkeley, CA.

It is currently being maintained by tcpdump.org.

The current version is available via http:

http://www.tcpdump.org/

The original distribution is available via anonymous ftp:

ftp://ftp.ee.lbl.gov/tcpdump.tar.Z

IPv6/IPsec support is added by WIDE/KAME project. This program uses Eric Young's SSLeay library, under specific configuration.  

BUGS

Please send problems, bugs, questions, desirable enhancements, etc. to:

tcpdump-workers@tcpdump.org

Please send source code contributions, etc. to:

patches@tcpdump.org

NIT doesn't let you watch your own outbound traffic, BPF will. We recommend that you use the latter.

On Linux systems with 2.0[.x] kernels:

packets on the loopback device will be seen twice;
packet filtering cannot be done in the kernel, so that all packets must be copied from the kernel in order to be filtered in user mode;
all of a packet, not just the part that's within the snapshot length, will be copied from the kernel (the 2.0[.x] packet capture mechanism, if asked to copy only part of a packet to userland, will not report the true length of the packet; this would cause most IP packets to get an error from tcpdump);
capturing on some PPP devices won't work correctly.

We recommend that you upgrade to a 2.2 or later kernel.

Some attempt should be made to reassemble IP fragments or, at least to compute the right length for the higher level protocol.

Name server inverse queries are not dumped correctly: the (empty) question section is printed rather than real query in the answer section. Some believe that inverse queries are themselves a bug and prefer to fix the program generating them rather than tcpdump.

A packet trace that crosses a daylight savings time change will give skewed time stamps (the time change is ignored).

Filter expressions on fields other than those in Token Ring headers will not correctly handle source-routed Token Ring packets.

Filter expressions on fields other than those in 802.11 headers will not correctly handle 802.11 data packets with both To DS and From DS set.

ip6 proto should chase header chain, but at this moment it does not. ip6 protochain is supplied for this behavior.

Arithmetic expression against transport layer headers, like tcp[0], does not work against IPv6 packets. It only looks at IPv4 packets.

Posted by heresyrt

NT 서비스 종속성 설정

sc.exe를 사용해서 서비스를 설정할 수 있습니다.

1.서비스 종속성 설정
sc.exe config MailReceiver depend= MSSQLSERVER
MailReceiver 서비스가 MSSQLSERVER 서비스에 종속됩니다.
MSSQLSERVER 서비스가 실행이 되는 중에만 MailReceiver 서비스가 실행됩니다.
MailReceiver 서비스를 시작할 경우, MSSQLSERVER 서비스가 실행 중이 아니면 MSSQLSERVER 서비스를 실행시킨 후 MailReceiver 서비스를 실행합니다.
MSSQLSERVER 서비스를 중지할 경우, MailReceiver 서비스가 실행 중이면 MailReceiver 서비스를 종료한 후 MSSQLSERVER 서비스를 종료합니다.

2.서비스 종속성 제거
sc.exe config MailReceiver depend= ""
MailReceiver 서비스가 실행 중인 상태에서 MSSQLSERVER 서비스를 중지하고자 하면 위와 같이 종속성을 해제한 후 MSSQLSERVER 서비스를 중지해야 합니다.

@ 서비스 자동 설정 : sc.exe config MailReceiver start= auto
@ 서비스 복구 옵션
sc.exe failure ClickSpyService reset= 3600 actions= restart/60000/restart/600000/restart/600000
Posted by heresyrt

Java 정규식

a tip-off 2008/01/25 17:36

복연 [wegra@wegra.org]
자바스터디 네트워크
[http://javastudy.co.kr]

 

어플리케이션들을 만들다 보면 종종 단어 검색, 메일 주소 점검, XML 문서의 무결성 확인 등과 같은 복잡한 문자열 처리 기능이 필요한 경우가 있게 마련이다. 이런 때에 패턴 매칭(pattern matching)이 자주 사용된다. Perl과 sed, awk와 같은 언어들은 일치하는 텍스트를 검색하기 위해, 패턴을 정의하는 문자들과 정규표현식을 사용해 향상된 패턴 매칭 능력을 제공해 주고 있다. 자바에서 패턴 매칭을 사용하려면 StringTokenizer 클래스와 수많은 charAt, substring 메소드를 동원해야만 한다. 하지만 이런 방식은 종종 아주 복잡하고 지저분한 코드를 만들어내곤 한다.

 

하지만 모두 지금까지의 이야기일 Java 2 Platform, Standard Edition(J2SE) 1.4 넘어오면서 정규 표현식을 다룰 있는 java.util.regex라는 새로운 패키지가 추가되었다. 이제 자바에도 정규 표현식의 강력함을 맛볼 있는 메타 캐릭터들을 사용할 있게 되었다.

 

이번 글에서는 정규 표현식에 대해 간단히 설명하고, 아래의 과정에 따라 java.util.regex 패키지를 통해 정규 표현식을 활용하는 방법에 대해 자세히 설명하도록 하겠다.

 

l        단어 바꾸기

l        메일 주소 점검

l        파일에서 제어 문자 제거

l        파일 검색

 

( 글의 예제들을 실행시켜보려면 J2SE 1.4 호환 컴파일러와 가상머신이 필요함)

 

정규 표현식 만들기

정규표현식이란 여러 문자열들의 공통적인 특성을 기술하는 문자들의 패턴이다. java.util.regex 패키지를 보면 입력 데이터로부터 패턴을 찾고 수정할 있는 다양한 방법들이 제공됨을 확인할 있을 것이다.

 

정규표현식의 가장 단순한 형태는 ‘Java’, ‘programming’ 같은 일반적인 문자열이다. 또한 메일 주소와 같이 특수한 포맷을 갖는 문자열을 검증 등도 가능하다.

 

정규 표현식에는 일반 문자들과 특수 문자들이 혼용되어 사용된다.

 

\$

^

.

*

+

?

[

]

\.

 

 

 

 

‘\’ 시작하는 문자열을 제외한 모든 문자들은 보통 문자를 의미한다.

 

특수 문자들은 물론 고유한 기능을 갖고 있다. 예를 들어 ‘.’ 경우 라인 종결 문자를 제외한 어떤 문자와도 대응될 있다. 따라서 정규표현식s.n ‘sun’, ‘son’ 등과 같이 ‘s’ 시작하고 ‘n’ 으로 끝나는 자로 문자열 어떤 것이든 있다.

 

이와 같이 우리는 정규표현식에서 제공되는 여러 특수 문자들을 통해 줄의 시작 단어를 찾거나, 특정 범위의 문자 찾기, 대소문자 구별 없이 찾기, 정확히 일치하는 단어 찾기 등의 작업을 쉽게 처리할 있다.

 

java.util.regex 패키지에서 제공하는 정규표현식은 Perl 언어에서의 정규표현식 사용법과 같기 때문에 Perl 익숙한 사용자라면 같은 문법을 그대로 자바에도 적용할 있다. 만약 정규표현식에 익숙하지 않다면 아래 표가 많은 도움이 것이다.

Construct

Matches

Characters

 

X

The character x

\\

The backslash character

\0n

The character with octal value 0n (0 <= n <= 7)

\0nn

The character with octal value 0nn (0 <= n <= 7)

\0mnn

The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)

\xhh

The character with hexadecimal value 0xhh

\uhhhh

The character with hexadecimal value 0xhhhh

\t

The tab character ('\u0009')

\n

The newline (line feed) character ('\u000A')

\r

The carriage-return character ('\u000D')

\f

The form-feed character ('\u000C')

\a

The alert (bell) character ('\u0007')

\e

The escape character ('\u001B')

\cx

The control character corresponding to x

 

 

Character Classes

[abc]

a, b, or c (simple class)

[^abc]

Any character except a, b, or c (negation)

[a-zA-Z]

a through z or A through Z, inclusive (range)

[a-z-[bc]]

a through z, except for b and c: [ad-z] (subtraction)

[a-z-[m-p]]

a through z, except for m through p: [a-lq-z]

[a-z-[^def]]

d, e, or f

 

 

Predefined Character Classes

.

Any character (may or may not match line terminators)

\d

A digit: [0-9]

\D

A non-digit: [^0-9]

\s

A whitespace character: [ \t\n\x0B\f\r]

\S

A non-whitespace character: [^\s]

\w

A word character: [a-zA-Z_0-9]

\W

A non-word character: [^\w]

보다 자세한 설명과 예제는 J2SE 1.4 API 문서의 java.util.regex.Pattern 참조하도록 하자.

 

클래스와 메소드

 

Pattern 클래스

Pattern 객체는 Perl 문법과 비슷한 형태로 정의된 정규표현식을 나타낸다.

 

문자열로 정의한 정규표현식은 사용되기 전에 반드시 Pattern 클래스의 인스턴스로 컴파일되어야 한다. 컴파일된 패턴은 Matcher 객체를 만드는 사용되며, Matcher 객체는 임의의 입력 문자열이 패턴에 부합되는 여부를 판가름하는 기능을 담당한다. 또한 Pattern 객체들은 비상태유지 객체들이기 때문에 여러 개의 Matcher 객체들이 공유할 있다.

 

다음은 Pattern 클래스의 주요 메소드들에 대한 설명이다.

 

static Pattern compile(String regex) : 주어진 정규표현식으로부터 패턴을 만들어낸다(이를컴파일 한다 표현한다).
static Matcher matcher (CharSequence input) :
입력 캐릭터 시퀀스에서 패턴을 찾는 Matcher 객체를 만든다.
String[] pattern() :
컴파일된 정규표현식을 String 형태로 반환한다.
String[] split(CharSequence input) :
주어진 입력 캐릭터 시퀀스를 패턴에 따라 분리한다.

 

/*

 * split 메소드를 이용해 입력 시퀀스를 콤마(‘,’) 공백 문자를 기준으로

 * 나눈다.

 */

import java.util.regex.*;

 

public class Splitter {

    public static void main(String[] args) throws Exception {

        // 이상의 연속된 ‘,’ 공백문자를 의미하는 패턴을 만든다.

        Pattern p = Pattern.compile("[,{space}]+");

        // 패턴에 따라 입력 문자열을 쪼갠다.

        String[] result =

                 p.split("one,two, three   four ,  five");

        for (int i=0; i<result.length; i++)

            System.out.println(result[i]);

    }

}

 

Matcher 클래스

Matcher 객체는 특정한 문자열이 주어진 패턴과 일치하는가를 알아보는데 이용된다. Matcher 클래스의 입력값으로는 CharSequence라는 새로운 인터페이스가 사용되는데 이를 통해 다양한 형태의 입력 데이터로부터 문자 단위의 매칭 기능을 지원 받을 있다. 기본적으로 제공되는 CharSequence 객체들은 CharBuffer, String, StringBuffer 클래스가 있다.

 

Matcher 객체는 Pattern 객체의 matcher 메소드를 통해 얻어진다. Matcher 객체가 일단 만들어지면 주로 가지 목적으로 사용된다.

 

l        주어진 문자열 전체가 특정 패턴과 일치하는 가를 판단(matches).

l        주어진 문자열이 특정 패턴으로 시작하는가를 판단(lookingAt).

l        주어진 문자열에서 특정 패턴을 찾아낸다(find).

 

이들 메소드는 성공 true 실패 false 반환한다.

 

또한 특정 문자열을 찾아 새로운 문자열로 교체하는 기능도 제공된다.

 

appendRepalcement(StringBuffer sb, String replacement) 메소드는 일치하는 패턴이 나타날 때까지의 모든 문자들을 버퍼(sb) 옮기고 찾아진 문자열 대신 교체 문자열(replacement) 채워 넣는다. 또한 appendTail(StringBuffer sb) 메소드는 캐릭터 시퀀스의 현재 위치 이후의 문자들을 버퍼(sb) 복사해 넣는다. 다음 절에 나오는 예제 코드를 참고하도록 하자.

 

CharSequence 인터페이스

 

CharSequence 인터페이스는 다양한 형태의 캐릭터 시퀀스에 대해 일관적인 접근 방법을 제공하기 위해 새로 생겨났다. 기본적으로 String, StringBuffer, CharBuffer 클래스가 이를 구현하고 있으므로 적절한 것을 골라 사용하면 되며, 인터페이스가 간단하므로 필요하면 직접 이를 구현해 새로 하나 만들어도 된다.

 

Example Regex Scenarios

아래 코드는 J2SE 1.4 도큐먼트의 예제를 완성한 것이다.

 

/*

 * 코드는 "One dog, two dogs in the yard." 라는 문자열을

 * 표준 출력을 통해 출력한다.

 */

import java.util.regex.*;

 

public class Replacement {

    public static void main(String[] args)

                         throws Exception {

        // ‘cat’이라는 패턴 생성

        Pattern p = Pattern.compile("cat");

        // 입력 문자열과 함께 매쳐 클래스 생성

        Matcher m = p.matcher("one cat," +

                       " two cats in the yard");

        StringBuffer sb = new StringBuffer();

        boolean result = m.find();

        // 패턴과 일치하는 문자열을 ‘dog’으로 교체해가며

        // 새로운 문자열을 만든다.

        while(result) {

            m.appendReplacement(sb, "dog");

            result = m.find();

        }

        // 나머지 부분을 새로운 문자열 끝에 덫붙인다.

        m.appendTail(sb);

        System.out.println(sb.toString());

    }

}

 

메일 주소 포맷 확인

다음 코드는 주어진 입력 시퀀스가 메일 주소 포맷인가를 판단한다. 코드는 가능한 모든 형태의 메일 주소를 확인하는 것은 아니니 필요하면 코드를 추가해 사용하자.

 

/*

* 메일 주소에서 잘못된 문자 검사

*/

public class EmailValidation {

   public static void main(String[] args)

                                 throws Exception {

                                

      String input = "@sun.com";

      //메일 주소가 ‘.’이나 ‘@’ 같은 잘못된 문자로 시작하는 확인

      Pattern p = Pattern.compile("^\\.|^\\@");

      Matcher m = p.matcher(input);

      if (m.find())

         System.err.println("Email addresses don't start" +

                            " with dots or @ signs.");

      //’www.’으로 시작하는 주소를 찾는다.

      p = Pattern.compile("^www\\.");

      m = p.matcher(input);

      if (m.find()) {

        System.out.println("Email addresses don't start" +

                " with \"www.\", only web pages do.");

      }

      p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");

      m = p.matcher(input);

      StringBuffer sb = new StringBuffer();

      boolean result = m.find();

      boolean deletedIllegalChars = false;

 

      while(result) {

         deletedIllegalChars = true;

         m.appendReplacement(sb, "");

         result = m.find();

      }

 

m.appendTail(sb);

 

      input = sb.toString();

 

      if (deletedIllegalChars) {

         System.out.println("It contained incorrect characters" +

                           " , such as spaces or commas.");

      }

   }

}

 

파일에서 제어 문자 제거

 

/*

* 지정된 파일에서 제어 문제를 찾아 제거한다.

*/

import java.util.regex.*;

import java.io.*;

 

public class Control {

    public static void main(String[] args)

                                 throws Exception {

                                

        //파일 객체 생성

        File fin = new File("fileName1");

        File fout = new File("fileName2");

        //입출력 스트림 생성

        FileInputStream fis =

                          new FileInputStream(fin);

        FileOutputStream fos =

                        new FileOutputStream(fout);

 

        BufferedReader in = new BufferedReader (

                       new InputStreamReader(fis));

        BufferedWriter out = new BufferedWriter (

                      new OutputStreamWriter(fos));

 

        // 제어문자를 의미하는 패턴 생성

        Pattern p = Pattern.compile("{cntrl}");

        Matcher m = p.matcher("");

        String aLine = null;

        while((aLine = in.readLine()) != null) {

            m.reset(aLine);

            //제어 문자들을 문자열로 대체

            String result = m.replaceAll("");

            out.write(result);

            out.newLine();

        }

        in.close();

        out.close();

    }

}

 

파일 검색

 

/*

 * .java 파일에서 주석을 찾아 출력한다.

 */

import java.util.regex.*;

import java.io.*;

import java.nio.*;

import java.nio.charset.*;

import java.nio.channels.*;

 

public class CharBufferExample {

    public static void main(String[] args) throws Exception {

        // 주석을 나타내는 패턴 생성

        Pattern p =

            Pattern.compile("//.*$", Pattern.MULTILINE);

       

        // 소스파일

        File f = new File("Replacement.java");

        FileInputStream fis = new FileInputStream(f);

        FileChannel fc = fis.getChannel();

       

        // 소스 파일로부터 CharBuffer 생성

        ByteBuffer bb =

            fc.map(FileChannel.MAP_RO, 0, (int)fc.size());

        Charset cs = Charset.forName("8859_1");

        CharsetDecoder cd = cs.newDecoder();

        CharBuffer cb = cd.decode(bb);

       

        // 매칭 작업 수행

        Matcher m = p.matcher(cb);

        while (m.find())

            System.out.println("Found comment: "+m.group());

    }

}

 

결론

이제 자바의 패턴 매칭 능력은 다른 언어 부럽지 않은 수준까지 다다르게 되었다. 정규 표현식은 데이터베이스 또는 다른 어플리케이션에 데이터를 넘기기 전에 데이터가 정확한 포맷을 지키고 있는 검증할 , 또는 다양한 목적의 관리 작업에 사용될 있을 것이다. 간단히 말해 패턴 매칭이 필요한 모든 자바 프로그램에서 이제 정규표현식을 사용할 있게 되었다.

Posted by heresyrt

AJax - JQuery

a tip-off 2007/11/13 17:17

가볍고 쉬운 Ajax - jQuery 시작하기

 출처 : http://blog.naver.com/kissin/70018447897

 

시작 하기 전에

 

jQuery는 2006년 초에 John Resig가 개발한 자바스크립트 라이브러리 이다. 전체 라이브러리가 55kb밖에는 안되는 초 경량이면서도 누구나 쉽게 브라우져 기반의 자바스크립트 프로그래밍을 쉽게 할 수 있을 뿐더러, Ajax또한 쉽게 구현 할 수 가 있다. 또한 플러그인 방식의 확장을 지원하여, 현재 많은 수의 플러그인을 확보하고 있다.

나온지는 얼마 안되었지만 수백여개의 사이트가 사용할 만큼 안정적이며, 유명한 라이브러리 이다. 구지 비교하자면 prototype이라는 기존 유명 라이브러리와 비교가 가능하겠지만, 더욱 간단하며, 쉽다는것을 장점으로 꼽고 있다.(사실 본인은 prototype을 잘 모른다. 따라서 기존 개발자들의 의견을 빌린것이다. 어느것이 더 좋다는 표현이 아님을 알아달라)

무엇이 짧은 시간안에 jQuery를 유명하게 하였을까? 이런 호기심을 가지고 깊이 살펴본 결과 그 이유를 알 수 있었다. 작고, 쉽고, 그러나 강력하다는 것이 그 이유이다. 따라서 이런 본인의 경험을 공유하고자 이글을 올린다.

이 글은 jQuery의 튜토리얼문서를 기반으로하여 작성 되었다. 따라서 예제의 상당 부분은 동일하다, 단, 직접 프로그래밍을 통해 소스를 돌려보고 그 경험을 글로 올리는것이니 만큼 그냥 번역 보다는 더 나을 것으로 판단 한다.

참고로 이글에서 Ajax는 비동기 통신의 경우에만 국한 하겠다. 그 이유는 jQuery에서 Ajax라는 별도 네임스페이스로 라이브러리를 지원하기 때문이다.

 

자바스크립트 전용 IDE 소개 - Aptana

 프로그래머들 중에는 IDE를 싫어하는 사람도 있다. 그러나 나는 없는것보다는 있는것이 더 낳다고 생각한다. 특히 한 언어를 위한 전용 환경을 지원할 경우는 더욱 그러하다. 브라우져 기반의 자바스크립트 프로그래밍을 하다보면 가장 어려운 점이 디버깅이다. printf디버거도 어려울 경우가 많다.(printf디버거는 디버깅을 위해 필요한 값을 출력하여 확인 하는 방법을 말한다.-본인이 만들어낸 용어이다.) 특히 브라우져의 경우는 로컬파일을 사용할 수 없어 화면을 이용한 값의 출력에 의존하여야 함으로 루프값을 출력할 경우는 거의 죽음이고, HTML태그를 생성하여 이곳에 이벤트를 결합하고, 코딩하는것을 반복하는 동적 HTML프로그래밍은 더욱 디버깅이 어렵다. 따라서 브라우져의 플러그인과 결합된 디버거를 사용하는것이 매우 도움이 된다.

Firefox용 Firebug가 대표적인 것인데, 가장 많이 사용하는 디버거 이기도 하다. 그러나 편집기와 독립된 형태로 사용해야 함으로 수정 작업 시 불편함이 따른다. 이러한 점을 개선하려면 역시 디버거와 편집기를 포함하는 전용 IDE가 필요하다.

한가지더 이야기 하면, 기존 Eclipse와 같은 IDE에서 지원하는 Code Inspector기능의 필요를 들 수 있다. 사실 한 언어에 익숙한 사람이면 이 기능이 불편 하다. 매번 객체명뒤 점을 찍어 객체의 맴버를 보는 것은 그것을 아는 사람에게는 편집속도만 떨어뜨릴 뿐이다. 그러나 언어에 익숙치 않다거나, 남이 제공한 라이브러리를 사용할 경우는 이기능이 매우 유용하다. 특히 해당 맴버의 간단한 도움말까지 표시되면 API문서를 일일이 그때마다 검색하지 않아도 되어서 편리하다.

기존 자바 스크립트 편집기는 사실 이러한 기능이 부족한것이 사실 이었다. 그러나 지금 소개할 Aptana는 자바스크립트 전용 IDE를 표방한 몇 안되는 IDE중 하나이다. 이클립스 기반에 프러그인으로 개발되고 배포는 리치클라이언트와 플러그인 방식 모두를 지원한다. 따라서 기존 설치된 이클립스에서도 사용할 수 있고, 별도 설치를 통해 독립적인 IDE로 사용 할수도 있다. 다음은 Aptana의 실행 화면이다.

aptana-kissin.jpg

특히 Code Inspector가 매력 적이다. 노란 색으로 나오는 도움말도 매우 유용하다.

aptana2-kissin.jpg

Apatana의 설치는 쉽다. 또한 무료로 사용 할 수 가 있다. (http://www.aptana.org/)

사용법은 기존 Eclipse와 동일하다. 단 디버거를 사용하려면 Firefox가 설치 되어 있어야 한다.

또한 기존 Ajax라이브러리들도 지원하는데, jQuery도 지원한다. 위 화면에서 객체의 도움말이 나올 수 있는것은 이 때문이다. 프로젝트 생성 시 jQuery프로젝트를 선택하여 생성 하면 된다.

 

jQuery 사용

위에서 소개한 Aptana를 설치 하였다면, 별도 jQuery설치는 필요 없다. 하지만 설치가 어려운것은 아니다. jQuery라이브러리는 55kb짜리 파일 하나로 되어 있다. 이를 HTML에 사용 선언을 하여 주면 된다.

 

<html>
  <head>
     <script type="text/javascript" src="path/jquery.js"></script>
     <script type="text/javascript">
       // Your code goes here
     </script>
   </head>
  <body>
    <a href="http://jquery.com/">jQuery</a>
   </body>
</html>

 

기존 자바 스크립트 라이브러리 사용과 차이가 없다. 단, 압축버젼과 그렇지 않은 버젼 두개의 파일을 제공하는데, 프로그래밍을 할 때는 디버깅을 위해 압축하지 않은 버젼의 파일을 사용하고, 배포할 경우 압축된 버젼을 사용하는 것이 좋다.

 

jQuery 의 시작 이벤트

보통의 자바스크립트 프로그래머들은 브라우져의 document가 모두 다운로드 되어진 상태에서 코드를 시작하기위해 다음과 같은 이벤트에 스크립트 코드를 넣는다.

  window.onload = function(){ ... }

그러나 이 경우 이미지 까지 다운로드가 모두 완료 된 후 이벤트가 호출되기 때문에, 큰이미지의 경우 실행속도가 늦은 것처럼 사용자에게 보일 수 있다. 따라서 jQuery는 이러한 문제를 해결하기위해 다음과 같은 이벤트를 제공한다.

 

$(document).ready(function(){
   // 이곳에 코드를 넣으면 된다.
});

 

 이 이벤트는 브라우져의 document(DOM)객체가 준비가 되면 호출이 된다. 따라서 이미지 다운로드에 의한 지연이 없다.

위 코드는 다음과 같이 생략하여 사용 가능하다.

 

$(function() { // run this when the HTML is done downloading });
사용자 이벤트 처리 - 클릭이벤트의 예

특정 태그를 클릭 했을경우 이벤트의 처리를 jQuery에서 어떻게 처리 하는지를 살펴 보자. 다음은 위 HTML예제의 앵커(a)태그 클릭 시 이벤트를 처리하는 코드 이다.

$("a").click(function(){
alert("Thanks for visiting!");
});

jQuery에서 이벤트 처리는 콜백함수를 통해 수행된다. 이코드는 HTML에 있는 모든 앵커 태그의 클릭 시 팦업창을 통해 메시지를 출력해 준다.

코드를 보면 $()로된 문법을 볼 수 있을 것이다. 이것은 jQuery의 셀렉터 이다. $("a")가 의미하는 것은 HTML(브라우져의 DOM)에서 앵커태그 모두를 의미한다. 이후 .click()메소드는 이벤트 메소드로서 이곳에 콜백함수를 파라메타로 넣어 이벤트 처리를 수행 하는것이다. 함수는 위에서 처럼 익명(function(){...})이나 선언된 함수 모두를 사용할 수 있다.

jQuery의 셀렉터

$()로 시작하는 셀렉터를 좀더 살펴보자. jQuery는 HTML, DOM객체등을 CSS나 XPATH의 쿼리방법과 동일한 방법으로 선택 한다. 앞선 예처럼 문자열로 특정 태그를 선택하는 것은 CSS를 작성해 본 프로그래머라면 익숙할 것이다. 이와 같은 방법 외에도 다음과 같이 태그의 id를 통해 선택 할 수 있다.

$(document).ready(function() {
$("#orderedlist").addClass("red");
});

위 코드는 id가 orderedlist인 태그에 red라는 CSS 클래스를 할당하는 코드 이다. 만약 이태그가 하위 태그를 가지고 있다면 다음과 같이 선택 할 수 있다.

$(document).ready(function() {
$("#orderedlist > li").addClass("blue");
});

이코드는 id가 orderedlist인 태그의 하위 태그 중 <li> 태그 모두에 blue라는 CSS 클래스를 할당하는 코드 이다. 이코드는 jQuery메소드를 이용 다음과 같이 바꾸어 사용 할 수도 있다.

$(document).ready(function() {
$("#orderedlist").find("li").each(function(i) {
$(this).addClass("blue");
});
});

한가지 다른 점은 모든 태그에 동일하게 CSS 클래스를 적용하는 방식이 아닌 개별 태그를 선택하여 적용할 수 있다는 것이다.

XPath를 사용하는 예를 다음과 같은 것을 들 수 있다

//절대 경로를 사용하는 경우

$("/html/body//p")
$("/*/body//p")
$("//p/../div")

//상대경로를 사용하는 경우

$("a",this)
$("p/a",this)

다음과 같이 두 방식을 혼용하여 사용 할 수도 있다.

//HTML내 모든 <p>태그중 클래스속성이 foo인 것 중 내부에 <a> 태그를 가지고 있는것

$("p.foo[a]");

//모든 <li>태그 중 Register라는 택스트가 들어있는 <a> 태그

$("li[a:contains('Register')]");

//모든 <input>태그 중 name속성이 bar인 것의 값

$("input[@name=bar]").val();

이외에도 jQuery는 CSS 3.0 표준을 따르고 있어 기존 보다 더많은 쿼리 방법을 지원하고 있다. 자세한것은 jQuery의 API 설명을 참고 하라(http://docs.jquery.com/Selectors)

Chainability

jQuery는 코드의 양을 줄이기 위해 특별한 기능을 제공한다. 다음 코드를 보자

$("a").addClass("test").show().html("foo");

<a>태그에 test라는 CSS 클래스를 할당한다. 그후 태그를 보이면서 그안에 foo라는 텍스트를 넣는다. 이런 문법이 가능한 이유는 $(), addClass(), show()함수 모두가 <a>태그에 해당하는 객체를 결과로 리턴해주면 된다. 이를 Chainability라 한다. 좀더 복잡한 경우를 보자

$("a")
.filter(".clickme")
.click(function(){
alert("You are now leaving the site.");
})
.end()
.filter(".hideme")
.click(function(){
$(this).hide();
return false;
})
.end();

// 대상 HTML이다

<a href="http://google.com/" class="clickme">I give a message when you leave</a>
<a href="http://yahoo.com/" class="hideme">Click me to hide!</a>
<a href="http://microsoft.com/">I'm a normal link</a>

중간에 end()함수는 filter()함수로 선택된 객체를 체인에서 끝는 역할을 한다. 위에서는 clickme클래스의 <a>태그 객체를 끊고 hideme를 선택하는 예이다. 또한 this는 선택된 태그 객체를 말한다.

이런 Chainability를 지원 하는 jQuery메소드들에는 다음과 같은 것들이 있다.

  • add()
  • children()
  • eq()
  • filter()
  • gt()
  • lt()
  • next()
  • not()
  • parent()
  • parents()
  • sibling()
Callbacks

위에서 click()이벤트를 콜백함수를 통해처리하는 코드를 살펴 보았다. 콜백함수는 기존 자바나 .NET의 그것과 같다. 다음 코드를 보자

$.get('myhtmlpage.html', myCallBack);

먼저 $.get()은 서버로 부터 HTML(또는 HTML 조각)을 가져오는 함수 이다. 여기서 myCallBack함수는 전송이 완료 되면 호출되는 콜백 함수 이다. 물론 앞선 예의

click()이벤트 콜백처럼 익명함수 function(){}을 사용 해도 된다. 그러나 이와 같이 미리 선언된 함수를 콜백으로 사용할 경우 파라메타의 전달 방법은 좀 다르다. 흔히 다음과 같이 하면 될것이라 생각할 것이다.

$.get('myhtmlpage.html', myCallBack(param1, param2));

그러나 위와 같은것은 자바스크립트의 클로져(closure)사용에 위배가 된다. 클로져는 변수화 될수 있는 코드 블록을 이야기한다. 즉 스트링변수와 같이 파라메타로 전달될 수 있지만, 실행가능한 함수 인 것이다. 일반적으로 함수를 ()제외하고 이름만을 사용하면 클로져가 된다. 위의경우 $get()함수의 파라메타로 전달된 myCallBack함수는 클로져로 전달된것이 아닌 myCallBack()를 실행한 결과 값이 전달 된다. 따라서 다음과 같이 코드를 작성하여야 한다.

$.get('myhtmlpage.html', function(){
myCallBack(param1, param2);
});

만약 선언된 함수가 아닌 익명함수를 콜백으로 사용할경우는 다음과 같이 하면 된다.

$.get('myhtmlpage.html', function(param1, param2){
//이곳에 코드를 넣는다.
});

jQuery 의 애니메이션

HTML의 태그를 사라지고 나타내게 하거나, 늘리고 줄이고, 이동시키는 애니매이션 동작은 많이 사용하는 기는 중 하나이다. jQuery는 다양안 애니메이션 기능을 메소드를 통해 제공한다. 다음 코드를 보자

$(document).ready(function(){
$("a").toggle(function(){
$(".stuff").hide('slow');
},function(){
$(".stuff").show('fast');
});
});

이코드는 <a>태그중 stuff클래스가 할당된것을 토글로 느리게 감추고, 빨리 보이게 하는 함수 이다.

다음은 animate()메소드를 이용하여 여러 애니메이션을 합쳐 실행하는 예이다.

$(document).ready(function(){
$("a").toggle(function(){
$(".stuff").animate({ height: 'hide', opacity: 'hide' }, 'slow');
},function(){
$(".stuff").animate({ height: 'show', opacity: 'show' }, 'slow');
});
});

위 코드는 높이와 투명도를 동시에 천천히 사라지고, 나타나게 하는 코드 이다.

jQuery에서의 Ajax

Ajax는 서버와의 비동기 통신을 말한다. 일반적으로 Ajax하면 요즘은 자바스크립트를 이용한 브라우져의 동적 DOM의 처리, 즉 DHTML, CSS등을 포함하지만, jQuery에서는 Ajax라는 네임스페이스를 통해 비동기 서버 통신을 하는것을 말한다.먼저 다음 예를 보자

$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
})

이 예는 GET방식으로 서버에서 자바스크립트를 로딩하고 실행하는 코드 이다.

다음 예를 보자

$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});

이는 서버로 부터 POST방식으로 파라메터를 주어 데이터를 가져온 후 이를 success콜백을 이용해 처리하는 코드이다. 아마 Ajax에서 가장 많이 사용하는 코드일 것이다. success말고도 $.ajax()함수는 다양한 옵션을 제공한다. 자세한 내용은 API설명을 참조하라 (http://docs.jquery.com/Ajax)

다음 예는 이 옵션 중 async(비동기)방식을 사용할지 아닐지를 사용한 코드이다.

var html = $.ajax({
url: "some.php",
async: false
}).responseText;

맺으며...

지금까지 jQuery에 대해 간단히 살펴 보았다. 혹자는 Dojo나 Extjs와 같이 버튼, 그리드등의 위젯이 지원되지 않는다고 실망할 것이다.그러나 jQuery는 Plugin을 지원한다. 이중 Interface와 같은 플러그인은 그 완성도가 매우 높다. 이것 말고도 수백개의 플러그인들이 홈페이지를 통해 공개 되어 있다.(http://docs.jquery.com/Plugins)

하지만 내 경험상으로 그리드와 같은 복잡한 위젯이 아니더라도 자바스크립크를 이용한 동적인 홈페이지와 Ajax를 통한 비통기 통신만으로도 대부분의 고객 요구와 문제를 해결 할 수 있다. 실제로 jQuery는 MSNBC와 같은 유명한 많은 사이트에서 사용되고 있다.(http://docs.jquery.com/Sites_Using_jQuery)

따라서 어떤 서비스를 제공하느냐에 따라 필요한 위젯을 플러그인을 사용하거나 직접 개발하여 사용하는것이 더 나은 전략이라 생각한다. 사실 미리 만들어진 위젯도 나에게 맞추어 사용하기 위해서는 그래픽, CSS등 많은 부분을 손 대야 한다. 차라리 기본 원리를 알고 이를 확장하는 것이 좀더 전문적이고 어려운 문제를 해결 할 수 있는 길이라 생각 한다.

시간이 허락 한다면 꾸준히 jQuery의 개발 경험을 공유 하고 싶은 마음 이다.

출처 : http://blog.naver.com/kissin/70018447897

이 글은 스프링노트에서 작성되었습니다.

Posted by heresyrt

명령어

a tip-off 2007/11/07 17:39
  • 시스템 명령어

    • 주소록 가져오기 도구 : wabmig
    • 문자표 : charmap
    • 클립북(클립보드) 뷰어 : clipbrd
    • 시스템 구성유틸리티 : msconfig
    • ODBC 데이터 원본관리자 : odbcad32
    • Direct X 진단도구 : dxdiag
    • 디스크 정리 유틸 : cleanmgr
    • Windows용 Dr. Watson (프로그램 오류 디버거) : drwtsn32
    • IExpress 마법사(selefextracting 파일 작성기) : iexpress
    • 공유폴더 만들기 마법사 : shrpubw
    • 개체포장기(파일에 삽입할 패키지를 만드는 데 사용할 수 있는 도구) : packager
    • 사용자 정의 문자편집기 : eudcedit
    • 레지스트리 편집기 : regedit
    • 원격데스크톱 연결 : mstsc
    • 파일서명 확인 : sigverif
    • 동기화 관리 : mobsync
    • 시스템 구성 편집기 : sysedit
    • Windows 작업관리자 : taskmgr
    • Telnet Client : telnet
    • Microsoft 내레이터(텍스트 음성변환프로그램) : narrator
    • Windows 주소록 : wab
    • 파일 및 설정 전송 마법사 : migwiz
    • Windows Network Chat(채트) : winchat
    • Windows 버전 정보 : winver
    • 인증서 : certmgr.msc
    • 구성요소 서비스 : comexp.msc
    • 컴퓨터 관리 : compmgmt.msc
    • 장치관리자 : devmgmt.msc
    • 디스크 조각 모음 : diskmgmt.msc
    • 디스크 관리 : diskmgmt.msc
    • 이벤트 뷰어 : eventvwr.msc
    • 그룹정책 개체 편집기 : gpedit.msc
    • 인덱싱 서비스 : ciadv.msc
    • 로컬 사용자 및 그룹 : lusrmgr.msc
    • 성능 모니터링 : perfmon.msc
    • 이동식 저장소 관리 : ntmsmgr.msc
    • 이동식 저장소 운영자 요청 : ntmsoprq.msc
    • 로컬 보안 설정 : secpol.msc
    • Netmeeting : conf
    • Microsoft Windows 악성 소프트웨어 제거 도구 : mrt

     

     

이 글은 스프링노트에서 작성되었습니다.

Posted by heresyrt

  정규식 사용되는 String 객체의 메소드



    메소드                                                                                                 리턴값        
    match(reg)        매치된 결과들의 내용을 Array 객체로 리턴                           null
    search(reg)       첫 번째 매치되는 문자열의 시작 index 값                             -1
    replace(reg)      1.첫 번째 매치된 reg를 rep로 교체하여 리턴한다
                            2.g속성이 사용되면 매치된 모든 문자열을 교체하여 바뀐       원본문자열
                                 문자열 전체를 리턴한다.                              
    split(reg,[n])     문자열을 ㄱeg를 기준으로 잘라서 Array 객체로 리턴한다.      원본문자열
        

  정규식(Regular Expression)


   /^경훈/;    "경훈" 로 시작하는 문자열 한 행과 매치되는 메타문자  ^
   /경훈$/;    "경훈" 로 끝나는 문자열 한 행과 매치되는 메타문자    $
  /경훈/;      문자열 "경훈" 와 매치되는 정규식의 일반문자.


   정규식의 속성(i, g, m)
                              m = 여러 줄에 대한 검색.

    /주리/g;      g 속성은 문자열 전역검색
    /주리/i;        i 속성은 대문자와 소문자를 구분하지 않음
    /주리/gi;      g 와 i 속성( 대소문자 구분없이 전역검색)

--------------------------------------------------------------

       var rap = /\s/g;                                       // 공백검사 g 는 전역검색          

         nid  = document.form.id.value;                 // id 값
         nid = nid.replace(rap,"");                          // 공백을 제거한다.
       if(nid == "" || nid.length < 0){
         return false;
  }

--------------------------------------------------------------

-------------------------------------------------------------------------------
  정규식 문자   매치되는 문자     정규식 문자     매치되는 문자  (\ = 역슬러시 이다)
 
  \n            줄 바꿈 문자            \*              * 문자
  \r            리턴                        \+              + 문자
  \t            탭                           \?              ? 문자
  \v            수직 탭                   \(              ( 문자
  [\b]          Backspace 문자     \)              ) 문자
  \cX           컨트롤 문자 ^X       \[              [ 문자
  \/            / 문자                    \]              ] 문자
  \\            \ 문자                  \{              { 문자
  \.            . 문자                      \}              } 문자

----------------------------------------------------------------------------------

  정규식의 메타문자

 

  [] :  [abc]는 문자 "a","b","c" 중에 하나의 문자와 매치되는 것
       a   ┏ reg1 = /강/;   reg2=/아/;   reg3=/지/;
       b   ┗ reg4 = /[강아지]/;                           //  a,b 같은 의미

  [^] : [^abc]는 a b c 제외한 임의의 한 문자와 매치되는 것
           
  단축 문자 클래스
  
1.  /[a-z]/;                [abcdefghij...z] 같다
2.  /[A-Z]/;               [ABCD.........Z] 같다
3.  /[0-9]/;                [0123456789]  같다
4.  /[a-zA-Z0-9]/;     1,2,3 다 포함시킨다.
5.  /[^a-zA-Z0-9]/;     영문자와 숫자를 제외한 모든 문자에 매치


 메타문자           단축 문자 클래스
  \s       -->     [\t\n\r\f\v]       임의의 공백문자(출력 되지 않는 문자들)
  

  문자의 반복과 반복기호

   {} ?, + ,*


  괄호() 메타문자
    
  n1=/곰/; n2=/개/; n3=/말/; n4=/송아지/;  n5=/양/;
  reg = /[곰개말(송아지)양]/;
   
  reg1 = /D(HTML)?/;             "D", "DHTML" 과 매치된다
  reg2 = /D(HTML|html)?/;      "D", "DHTML" ,"html 과 매치된다.
  reg3 = /Ok{3}/;                   "Okkk" 에 매치된다
  reg4 = /(Ok){3}/;                 "OkOkOk" 에 매치된다.


() 부분표현식
 
  str = "문자열 javascript";
  reg = /(java)(script)/;
                                       // reg = /(java+)(script+)/;
   a = str.match(reg);         // Array 객체다   a[0],a[1].....


  단어의 경계나 공백에 매치되는 앵커 메타문자

 

   \s      /\sHTML\s/;   앞뒤로 공백이 있는 " HTML " 문자에 매치된다.
  \b      /HTML\b/;       "HTML" 로 끝나는 단어에 매치된다.
   -----------------------------------------------------------------------------
       예) reg = /^\d|[^a-zA-Z0-9]/g;    : 첫 글자가 숫자인 것 또는 영문자나 숫자가
                                                          아닌것과 매치

 --------------------------------------------------------------------------------

출처 : http://blog.naver.com/rakis77?Redirect=Log&logNo=70021929239

Posted by heresyrt

1. 개념잡기

일반화 시킨 표현. 이것을 정규표현이라고 요약할 수 있을 것 같다.
다음의 과정을 너무 쉽다 생각말고 따라오길 바란다.

- 감잡기

"12354" -> 숫자
"asdfasf" -> 알파벳
두 가지의 간단정규표현을 만들었다. 실생활의 보기와 비추어보자.
"길이가 3인 이름!"
위의 표현은 길이를 표시하는 방법이 없다. 조금 더 발전시켜서 "알파벳{3}"이런식
으로 길이를 표현할 수 있도록 한다. 그리고, "알파벳"란 것도 너무 길다 "알"
이라고 한 글자로 표현한다. 그러면 "길이가 3인 이름"은
"알{3}"으로 표시가 가능하다.
길이가 10인 숫자는 "수{10}"
"길이가 1인 알파벳이 나오고 그 다음에 길이가 3인 숫자가 나오는 문자열"! ->
"알{1}수{3}"얼핏이나마 감이 올 것이다.
"첫 글자는A, 그 다음은 아무 알파벳 5글자" -> "A알{5}"

- 조금 더

아이디는 대개 첫 글자는 영문이고 두 번째부터는 영문이나 숫자가 온다. 이것을
표현하기 위해선 이것 들 중에 하나란 의미를 갖는 새로운 표현이 필요하다.
"a,b,c,d 중에 하나" -> [abcd]
응용하면,
"알파벳이나, 숫자중 하나" -> [알수]
"[" 안에 있는 문자들의 순서는 의미가 없으며, 그 표현은 (클래스라고 한다.)
결국 한 글자를 말한다.
위에서 말한 "첫 글자는 영문, 두 번째 부터는 영문이나 숫자가 11자"를
표현하면, "알[알수]{11}".
그런데, 실제로 모든 아이디가 12자인 것은 아니다, 대개 4자부터 12자를 지원한다.
새로운 표현이 등장한다. "몇 자부터 몇 자"
"A가 3글자부터 12자" -> "A{3,12}"
"알파벳이나 숫자가 1자부터 100자" -> "[알수]{1,100}"
이제 아이디를 다시 정의하자.
"첫 글자는 영문, 영문이나 숫자가 3자부터 11자" -> "알[알수]{3,11}"

2. 표현식

지금 까지의 규칙에서 설명한 용어를 실제 정규표현에서 사용하는 표현으로 바꾸고,
다른 세부적인 옵션에 대해 알아보자.

: 다음의 글자가 특별한 문자임을 나타낸다. 때론, 그 다음 문자 자체를 의미하기
도 한다.
보기를 들면, "
"은 문자""과 문자"n" 두 글자와 매치되는 것을 의미하는 것이 아
닌,
새줄(New Line)을 의미하며, "\"은 첫 "" 다음 문자인 "" 자체를 의미한다.
즉, "\"은
""과 매칭된다.

^ : 입력문자열의 맨 처음을 의미한다. (맨 첫 글자가 아니라, 맨 처음이란 문맥적 의
미를
말한다. 아주 중요하다) 기본적으로 정규표현은 입력 문자열의 한 줄에만 적용된다.
하지만, 옵션에 따라 여러줄에 적용할 수도 있다. 그럴 경우에는 "^"는 "
"
나 "
"
다음의 위치를 의미한다.

$ : "^"는 반대로 입력 문자열의 맨 끝을 의미한다. 역시 여러줄에 정규표현이 적용

경우에는 "
"이나 "
"의 앞의 위치를 의미한다.

* : 이 문자 앞의 표현이 0번내지 무한번 반복될 수 있음을 말한다.
보기를 들면, /a*/은 "a", "", "aaaa", "aaaaa"와 매칭된다.
(0번이상은 없어도 된다는 것을 의미한다.)

+ : *와 같지만, 0번이상이 아니라 1번이상이라는 점을 제외하곤 /*/와 같다.

? : 앞의 표현이 0번 또는 1번. /do(es)?/는 "do", "does"와 매칭된다.

{n} : 앞의 표현이 n은 음수가 아닌 정수이어야 하며, 앞의 표현이
n번 매치되는 것을 말한다.

{n,} : 앞의 표현이 n은 음수가 아닌 정수이어야 하며, n번 이상
매치되는 것을 말한다.

{n,m} : 앞의 표현이 n번 이상 부터 m번 이하까지 매칭되는 것을
말하며, /*/는 /{0,}/과 같으며, /+/는 /{1,}/과 /?/는 /{0,1}/으로
표현 가능하다.

. : "
"을 제외한 한 글자를 뜻한다. 만일 모든 글자를 표현하고
싶다면("
"마저도 합친) /[.
]/을 사용하면 된다.

x|y : x 또는 y와 매칭된다. 보기를 들면, /z|food/는 "z" 또는
"food"와 매칭된다. /(z|f)ood/는 "zood" 또는 "food"와 매칭된다.
(참고로 괄호는 묶어준 것 이상의 의미가 있다.)

(패턴) : 해당 패턴과 매칭시키고, 그 부분을 특정 변수에 담는다.
그 변수 이름은 JScript는 $0~$9까지의 변수에 저장이 되고(Perl과 같다.),
VBScript에서는 SubMatches 컬렉션에 저장된다.
괄호기호 자체와 매치시키고 싶다면? /(/와 /)/를 사용한다.

(?:패턴) : 해당 패턴과 매칭은 시키지만, 그 부분을 특정 변수에
담지 않는다. 왜 이게 필요할까?
위의 보기에서 /(z|f)ood/는 "zood" 또는 "food"와 매칭된다고 했는데,
단순히 매칭의 목적으로 사용했지만, "zood"의 경우 "z"가 $0 이란
변수에 저장이 되고 말았다. 이러한 것을 막기 위해서 사용하는 것이
(?:패턴)이다.

(?=패턴) : (?:패턴)과 동일하지만, 패턴과 일치한 부분이후부터
다음 매치가 일어나지 않고 패턴 앞부터 다시 매칭이 진행된다.
즉, 룩업(lookup, lookahead)을 할 뿐이다. /Windows (?=95|98|NT|2000)/ 은
"Windows 2000"의 "Windows" 부분과 매칭이 되며 다음 매칭은
"2000" 다음 부터가 아닌 "Windows" 다음 부터 진행이 된다.

(?!패턴) : (?=패턴)과 반대다. /Windows (?=95|98|NT|2000)/ 은
"Windows 3.1"의 "Windows" 부분과 매칭이 된다.

[xyz] : "["안에 있는 표현중 하나를 의미한다.

[^xyz] : "["안에 있는 표현을 제외한 것중 하나를 의미한다.
"[^abc]"는 "plain"의 "p"때문에 매칭된다.

[a-z] : "a"부터 "z" 까지의 문자중 하나

[^a-z] : "a"부터 "z" 까지의 문자를 제외한 하나

? : 단어의 경계(단어와 공백, "
", "
"의 사이)와 매칭된다.
보기를 들면, "er?"는 "never"와는 매칭되지만, "verb"와는 매칭되지 않는다.

B : 단어의 경계가 아닌 것과 매칭된다. "erB"는 "verb"와는
매칭되지만, "never"와는 매칭되지 않는다.

cx : Ctrl+x 키와 매칭된다. "cc"는 Ctrl+C와 매칭된다. x의 범위는
[a-zA-Z]이며, 만일 이 이외의 문자를 사용한다면 "c"는 "c"와 동일하다.

d : [0-9]와 같다.

D : [^0-9]와 같다. 참고로 대문자는 소문자의 반대 의미를 갖는다.

f : 폼피드(form-feed) 문자를 의미하며, "x0c"와 "cL"과 동일하다.


: 새 줄(newline)를 의미하며, "x0a"와 "cJ"와 동일하다.


: 캐리지 리턴(carriage return)을 의미하며, "x0d"와 "cM"과 동일하다.

: 탭. "x09", "cI"과 동일

v : 버티컬 탭. "x0b", "cK"과 동일

s : 화이트스페이스를 의미한다. 화이트스페이스란 공백, 탭, 폼피드,
캐리지리턴등을 의미한다. [ f

v]과 동일("f"앞에 공백이 있다. 주의!)

S : "[^ f

v]"

w : "_"를 포함한 일반적인 단어에 사용되는 문자를 말한다.
"[A-Za-z0-9_]" 과 동일

W : "[^A-Za-z0-9_]"

xn : n은 2자리 16진수이며, 해당 16진수 코드와 매칭된다. "x412"는 16진수
41은 "A"이기 때문에 "A2"와 매칭된다.


um : 캡쳐한 매칭을 가리킨다(백레퍼런스, backreference).
"(.)1"은 연속된 두개의 문자열을 의미한다.

: "1"은 위에서 캡쳐한 매칭(backreference)를 가리킨다고 했는데,
만일 이 패턴앞에 어떠한 n개의 캡쳐한 표현이 있다면 백레퍼런스이지만,
그렇지 않은 경우에는 8진수로 간주하여 해당 코드의 문자와 매칭된다.

un : n은 4자리 UNICODE 이다. "u00A9"은 copyright 심볼인 "ⓒ"와 매칭된다.


greedy, non-greedy

? : 앞에서 설명했는데, 왜 또? 라고 생각할 것이다.
?은 문맥에 따라 특별한 의미를 갖는다.
패턴 "o*"는 "foooood"와 매칭된다. 당연하다! 하지만, "f"앞의 "o"와
매칭되는 것이 아니다!! "ooooo"와 매칭된 것이다. 즉, 기본으로
정규표현 매칭은 가장 큰 범위를 선택한다. 이것을 greedy하다고 한다.
하지만, 때론 작은 범위에 매칭시킬 필요가 있을 경우가 있다.
(이의 적절한 보기는 잠시 후에 나온다.) "o*?"가 방금 말한
non-greedy 매칭이다.
수량관련 문자인 "*", "+", "?", "{n}", "{n,}", "{n,m}" 다음에 "?"가
나오면 non-greedy 매칭이된다.
잠시, 위에서 "o*?"가 "o"와 매칭된다고 했는데 이상하게 생각한 분이
있었을 것이다. 맞다. "o*?"는 ""와 매칭되었다. "*"는 0개이상임을
잊어선 안된다. "o+?"가 "o"와 매칭된다.

4. 보기

- 웹 주소

"http://msdn.microsoft.com:80/scripting/default.htm"
위의 주소를 표현할 수 있는 정규표현은 아래와 같다.
/(w+)://([^/:]+)(:d*)?([^# ]*)/
$1 : http
$2 : msdn.microsoft.com
$3 : 80
$4 : /scripting/default.htm

- 중복된 단어를 하나로

중복된 영어단어를 하나로 합치기 위해선, 우선 단어를 찾아야한다.
그리고 단어는 앞 뒤가 단어의 경계이어야한다. (말이 참 이상하지만..)
따라서, 아래와 같은 1차 정규표현을 얻을 수 있다.

/?([a-z]+)?/

연속해서 동일한 두개의 단어... 앞에서 캡쳐한 표현을 다시 활용하면 된다.
그리고, 단어와 단어 사이엔 화이트스페이스가 있다.

/?([a-z]+)s+1?/

- HTML 태그 제거

HTML문서에서 태그를 제거한 문서를 추출하고자 한다.
태그는 "<"와 ">"로 감싸여 있다.

/<.*>.*/

그런데, 위의 정규표현을 HTML문서에 적용하여 해당 패턴을 "",
빈문자열로 바꾸면 문서는 빈 문서가 되고 만다.




....
...

greedy한 매칭이 기본값이라고 위에서 언급을 했다. 따라서,
위의 HTML 문서를 보면, ....로 생각할 수 있다.
따라서, 문서 전체가 사라지는 것이다. 이것을 막기 위해선 "*"뒤에 "?"를
추가하면 된다.

/<.*?>.*?/

아직 끝나지 않았다. :)

좀더 정제를 한다면, 올바른 HTML 문서는 <태그명>과
서로 일치한다. 이것도 적용한다면,

/<.(*?)>.(*?)/

위의 $1에 해당되는 부분을 좀 더 생각해보면, ">"를 제외한 문자로
볼 수 있다. 따라서 최종적으로 아래와 같이 정리된다.

/<(w+)[^>]*?>(.*?)/

- URL

/(?:^|")(http|ftp|mailto):(?://)?(w+(?:[.:@]w+)*?)(?:/|@)([^"?]*?)(?:?
([^?"]*?))?(?:$|")/

- float 상수

/^(((+|-)?d+(.d*)?)|((+|-)?(d*.)?d+))$/ -1.1 1.1 .9 .8






정규식 구문
정규식은 일반 문자(예: a에서 z)와 메타문자 로 알려진 특수 문자로 구성된 텍스트 패턴입니다. 패턴은 텍스트 본문을 검색할 때 일치하는 문자열을 하나 이상 설명합니다. 정규식은 검색되는 문자열과 일치하는 문자 패턴을 찾는 템플릿의 역할을 합니다.

일반적으로 볼 수 있는 몇 가지 정규식 예는 다음과 같습니다.

JScript VBScript 검색 /^[ ]*$/ "^[ ]*$" 빈 줄을 찾습니다.
/d{2}-d{5}/ "d{2}-d{5}" 2자리, 하이픈 및 5자리로 구성된 ID 번호를 찾습니다.
/<(.*)>.*/ "<(.*)>.*" HTML 태그를 찾습니다.



아래 표는 정규식 컨텍스트에 사용되는 모든 메타문자와 메타문자의 동작을 보여줍니다.

문자 설명 그 다음 문자를 특수 문자, 리터럴, 역참조, 또는 8진수 이스케이프로 표시합니다. 예를 들어, "n"은 문자 "n"을 찾고 "
"은 줄 바꿈 문자를 찾습니다. "\" 시퀀스는 ""를 찾고 "("는 "("를 찾습니다.
^ 입력 문자열의 시작 위치를 찾습니다. Multiline 속성이 설정되어 있으면 ^는 '
' 또는 '
'앞의 위치를 찾습니다.
$ 입력 문자열의 끝 위치를 찾습니다. Multiline 속성이 설정되어 있으면 $는 '
' 또는 'r'뒤의 위치를 찾습니다.
* 부분식의 선행 문자를 0개 이상 찾습니다. 예를 들어, "zo*"는 "z", "zoo" 등입니다. *는 {0,}와 같습니다.
+ 부분식의 선행 문자를 한 개 이상 찾습니다. 예를 들어, "zo+"는 "zo", "zoo" 등이지만 "z"는 아닙니다. +는 {1,}와 같습니다.
? 부분식의 선행 문자를 0개 또는 한 개 찾습니다. 예를 들어, "do(es)?"는 "do" 또는 "does"의 "do"를 찾습니다. ?는 {0,1}과 같습니다.
{ n } n 은 음이 아닌 정수입니다. 정확히 n 개 찾습니다. 예를 들어, "o{2}"는 "Bob"의 "o"는 찾지 않지만 "food"의 o 두 개는 찾습니다.
{ n ,} n 은 음이 아닌 정수입니다. 정확히 n 개 찾습니다. 예를 들어, "o{2}"는 "Bob"의 "o"는 찾지 않지만 "foooood"의 모든 o는 찾습니다. "o{1,}"는 "o+"와 같고, "o{0,}"는 "o*"와 같습니다.
{ n , m } m 과 n 은 음이 아닌 정수입니다. 여기서 m 은 n 보다 크거나 같습니다. 최소 n 개, 최대 m 개 찾습니다. 예를 들어, "o{1,3}"은 "fooooood"의 처음 세 개의 o를 찾습니다. "o{0,1}"은 "o?"와 같습니다. 쉼표와 숫자 사이에는 공백을 넣을 수 없습니다.
? 이 문자가 다른 한정 부호(*, +, ?, { n }, { n ,}, { n , m })의 바로 뒤에 나올 경우 일치 패턴은 제한적입니다. 기본값인 무제한 패턴은 가능한 많은 문자열을 찾는 데 반해 제한적인 패턴은 가능한 적은 문자열을 찾습니다. 예를 들어, "oooo" 문자열에서 "o+?"는 "o" 한 개만 찾고, "o+"는 모든 "o"를 찾습니다.
. "
"을 제외한 모든 단일 문자를 찾습니다. "
"을 포함한 모든 문자를 찾으려면 '[.
]' 패턴을 사용하십시오.
( pattern ) pattern 을 찾아 검색한 문자열을 캡처합니다. 캡처한 문자열은 VBScript의 경우 SubMatches 컬렉션, Jscript의 경우 $0 ... $9 속성을 이용하여 결과로 나오는 Matches 컬렉션에서 추출할 수 있습니다. 괄호 문자인 ( )를 찾으려면 "(" 또는 ")"를 사용하십시오.
(?: pattern ) pattern 을 찾지만 검색한 문자열을 캡처하지 않습니다. 즉, 검색한 문자열을 나중에 사용할 수 있도록 저장하지 않는 비캡처 검색입니다. 이것은 패턴의 일부를 "or" 문자(|)로 묶을 때 유용합니다. 예를 들어, 'industr(?:y|ies)는 'industry|industries'보다 더 경제적인 식입니다.
(?= pattern ) 포함 예상 검색은 pattern 과 일치하는 문자열이 시작하는 위치에서 검색할 문자열을 찾습니다. 이것은 검색한 문자열을 나중에 사용할 수 있도록 캡처하지 않는 비캡처 검색입니다. 예를 들어, "Windows(?=95|98|NT|2000)"는 "Windows 2000"의 "Windows"는 찾지만 "Windows 3.1"의 "Windows"는 찾지 않습니다. 예상 검색은 검색할 문자열을 찾은 후 예상 검색 문자열을 구성하는 문자 다음부터가 아니라 마지막으로 검색한 문자열 바로 다음부터 찾기 시작합니다.
(?! pattern ) 제외 예상 검색은 pattern 과 일치하지 않는 문자열이 시작하는 위치에서 검색할 문자열을 찾습니다. 이것은 검색한 문자열을 나중에 사용할 수 있도록 캡처하지 않는 비캡처 검색입니다. 예를 들어, "Windows(?!95|98|NT|2000)"는 "Windows 3.1"의 "Windows"는 찾지만 "Windows 2000"의 "Windows"는 찾지 않습니다. 예상 검색은 검색할 문자열을 찾은 후 예상 검색 문자열을 구성하는 문자 다음부터가 아니라 마지막으로 검색한 문자열 바로 다음부터 찾기 시작합니다.
x | y x 또는 y 를 찾습니다. 예를 들어, "z|food"는 "z" 또는 "food"를 찾습니다. "(z|f)ood"는 "zood" 또는 "food"를 찾습니다.
[ xyz ] 문자 집합입니다. 괄호 안의 문자 중 하나를 찾습니다. 예를 들어, "[abc]"는 "plain"의 "a"를 찾습니다.
[^ xyz ] 제외 문자 집합입니다. 괄호 밖의 문자 중 하나를 찾습니다. 예를 들어, "[^abc]"는 "plain"의 "p"를 찾습니다.
[ a-z ] 문자 범위입니다. 지정한 범위 안의 문자를 찾습니다. 예를 들어, "[a-z]"는 "a"부터 "z" 사이의 모든 소문자를 찾습니다.
[^ a-z ] 제외 문자 범위입니다. 지정된 범위 밖의 문자를 찾습니다. 예를 들어, "[^a-z]"는 "a"부터 "z" 사이에 없는 모든 문자를 찾습니다.
? 단어의 경계, 즉 단어와 공백 사이의 위치를 찾습니다. 예를 들어, "er?"는 "never"의 "er"는 찾지만 "verb"의 "er"는 찾지 않습니다.
B 단어의 비경계를 찾습니다. "erB"는 "verb"의 "er"는 찾지만 "never"의 "er"는 찾지 않습니다.
c x X 가 나타내는 제어 문자를 찾습니다. 예를 들어, cM은 Control-M 즉, 캐리지 리턴 문자를 찾습니다. x 값은 A-Z 또는 a-z의 범위 안에 있어야 합니다. 그렇지 않으면 c는 리터럴 "c" 문자로 간주됩니다.
d 숫자 문자를 찾습니다. [0-9]와 같습니다.
D 비숫자 문자를 찾습니다. [^0-9]와 같습니다.
f 폼피드 문자를 찾습니다. x0c와 cL과 같습니다.

줄 바꿈 문자를 찾습니다. x0a와 cJ와 같습니다.

캐리지 리턴 문자를 찾습니다. x0d와 cM과 같습니다.
s 공백, 탭, 폼피드 등의 공백을 찾습니다. "[ f

v]"와 같습니다.
S 공백이 아닌 문자를 찾습니다. "[^ f

v]"와 같습니다.
탭 문자를 찾습니다. x09와 cI와 같습니다.
v 수직 탭 문자를 찾습니다. x0b와 cK와 같습니다.
w 밑줄을 포함한 모든 단어 문자를 찾습니다. "[A-Za-z0-9_]"와 같습니다.
W 모든 비단어 문자를 찾습니다. "[^A-Za-z0-9_]"와 같습니다.
x n n 을 찾습니다. 여기서 n 은 16진수 이스케이프 값입니다. 16진수 이스케이프 값은 정확히 두 자리여야 합니다. 예를 들어, 'x41'은 "A"를 찾고 'x041'은 'x04'와 "1"과 같습니다. 정규식에서 ASCII 코드를 사용할 수 있습니다.
num num 을 찾습니다. 여기서 num 은 양의 정수입니다. 캡처한 문자열에 대한 역참조입니다. 예를 들어, '(.)1'은 연속적으로 나오는 동일한 문자 두 개를 찾습니다.
n 8진수 이스케이프 값이나 역참조를 나타냅니다. n 앞에 최소한 n개의 캡처된 부분식이 나왔다면 n 은 역참조입니다. 그렇지 않은 경우 n 이 0에서 7 사이의 8진수이면 n 은 8진수 이스케이프 값입니다.
nm 8진수 이스케이프 값이나 역참조를 나타냅니다. nm 앞에 최소한 nm개의 캡처된 부분식이 나왔다면 nm 은 역참조입니다. nm 앞에 최소한 n개의 캡처가 나왔다면 n 은 역참조이고 뒤에는 리터럴 m이 옵니다. 이 두 경우가 아닐 때 n과 m이 0에서 7 사이의 8진수이면 nm 은 8진수 이스케이프 값 nm을 찾습니다.
nml n 이 0에서 3 사이의 8진수이고 m 과 l 이 0에서 7 사이의 8진수면 8진수 이스케이프 값 nml 을 찾습니다.
u n n 은 4 자리의 16진수로 표현된 유니코드 문자입니다. 예를 들어, u00A9는 저작권 기호(©)를 찾습니다.






--------------------------------------------------------------------------------
Visual Basic Scripting Edition에서 정규 표현식 기능 이용하기
--------------------------------------------------------------------------------

정규 표현식이란 무엇인가요?
정규 표현식이란 무엇일까요? 정규 표현식은 복잡한 패턴 매칭 기능과 텍스트형 검색-대체 알고리즘을 개발할 수 있는 툴을 제공합니다. Perl, egrep, awk, 또는 sed 개발자에게 정규 표현식이 무엇이냐고 물어보면, 정규 표현식은 텍스트와 데이터를 조작할 때 사용할 수 있는 가장 강력한 유틸리티라고 대답할 것입니다. 개발자는 패턴을 만들어 특정 문자열을 매치키시킴으로써 데이터를 검색하거나 추출하거나 교체하는 일을 완벽하게 제어할 수 있습니다. 간단히 말해서, 정규 표현식을 정복하면 데이터도 정복할 수 있는 것입니다.

여기서는, VBScript 정규 표현식과 관련된 모든 개체를 설명하고, 일반적인 정규 표현식 패턴을 간략하게 살펴보고, 실제 코드로 정규 표현식을 사용하는 예를 들어보도록 합시다.

VBScript RegExp 개체
VBScript 5.0 버전은 정규 표현식을 하나의 개체로서 제공합니다. VBScript RegExp 개체는 설계 면에서 JScript의 RegExp 및 String 개체와 비슷하고, 구문 면에서는 Visual Basic과 일치합니다. 먼저, VBScipt RegExp 개체의 속성과 메소드에 관해 알아봅시다. VBScript RegExp 개체는 사용자에게 세 개의 속성과 세 개의 메소드를 제공합니다.

속성 메소드
Pattern Test(검색-문자열)
IgnoreCase Replace (검색-문자열, 대체-문자열)
Global Execute (검색-문자열

Pattern - 정규 표현식을 정의하는 데 사용되는 문자열. 이 속성은 정규 표현식 개체를 사용하기 전에 먼저 설정해야 합니다. Pattern에 관한 내용은 아래에 자세히 설명되어 있습니다.
IgnoreCase - 문자열 안에서 일치하는 문자가 발생할 모든 가능성에 대해 정규 표현식을 테스트해야 하는지를 나타내는 부울 논리 속성입니다. IgnoreCase의 기본 설정 값은 False입니다.
Global - 문자열 안에서 일치하는 문자가 발생할 모든 가능성에 대해 정규 표현식을 테스트해야 하는지 여부를 나타내는 읽기 전용 부울 논리 속성입니다. Global의 기본 설정 값은 False입니다.
Test (문자열) - Test 메소드는 문자열을 매개 변수로 받아 그 문자열이 정규 표현식에 일치하면 True를 반환하고 그렇지 않으면 False를 반환합니다.
Replace (검색-문자열, 대체-문자열) - Replace 메소드는 두 개의 문자열을 매개 변수로 받습니다. 검색-문자열 안에 정규 표현식과 일치하는 문자열이 있으면, 그 문자열을 대체-문자열로 바꾸고, 바뀐 새로운 문자열을 반환합니다. 만일 일치하는 문자열이 없으면, 원래의 검색-문자열을 반환합니다.
Execute (검색-문자열) - Execute 메소드는 Matches 컬렉션 개체를 반환하는 점만 제외하면 Replace 메소드의 작동과 비슷합니다. Matches 컬렉션 개체에는 정규 표현식에 일치하는 각 문자열에 대한 Match 개체가 들어 있습니다. 이 메소드는 원래의 문자열을 변경하지 않습니다.
더 자세한 내용과 예제 코드는,Microsoft Scripting Site 사이트를 참고하시기 바랍니다.

VBScript Matches 컬렉션 개체
앞에서 말했듯이, Matches 컬렉션 개체는 Execute 메소드를 실행한 경우에만 반환됩니다. 이 컬렉션 개체는 0개 이상의 Match 개체를 포함할 수 있으며, 이 개체의 속성은 읽기 전용입니다.

속성
Count
Item

Count -컬렉션 안에 있는 Match 개체의 개수를 나타내는 읽기 전용 값입니다.
Item - Matches 컬렉션 개체에서 Match 개체를 임의로 액세스할 수 있게 만드는 읽기 전용 값입니다. For-Next 루프를 사용하면, Matches 컬렉션 개체에서 Match 개체를 순서대로 액세스할 수도 있습니다.
더 자세한 내용과 예제 코드는, Microsoft Scripting Site 를 참고하시기 바랍니다.

VBScript Match 개체
각 Mathes 개체에는 0개 이상의 Match 개체가 들어 있습니다. 이 Match 개체들은 정규 표현식을 사용했을 때 성공적으로 일치한 문자열을 나타냅니다. 이 개체의 속성은 읽기 전용이며 일치하는 각 문자열에 대한 정보를 저장합니다.

속성
FirstIndex
Length
Value

FirstIndex - 원래 문자열 안에서 정규 표현식에 일치하는 문자열의 위치를 나타내는 읽기 전용 값입니다. 이 색인은 위치를 기록하는데 0 기준 오프셋(문장의 첫 위치가 0번째임을 뜻함)을 사용합니다.
Length - 일치된 문자열의 전체 길이를 나타내는 읽기 전용 값입니다
Value - 일치된 값이나 텍스트를 나타내는 읽기 전용 값입니다. 이 값은Match 개체를 액세스할 때 사용되는 기본 값이기도 합니다.
더 자세한 내용과 예제 코드는, Microsoft Scripting Site 를 참고하시기 바랍니다.

패턴은 어떤 형태인가?
자, 지금까지는 이 모든 것이 지나치게 훌륭하고 환상적인 것으로 느껴지셨겠지만 실제는 어떨까요? 정규 표현식은 그 자체가 하나의 언어라고 할 수 있지만, Perl에 익숙한 사용자들이라면 누구나 쉽게 사용할 수 있습니다. VBScript는 Perl로부터 패턴 셋을 유도하기 때문에, 주요 기능도 Perl과 비슷합니다. 그러면, 정규 표현식을 정의하는 데 사용되는 패턴 셋 몇 가지를 살펴보도록 합시다. 패턴 셋은 여러 범주와 영역으로 분류할 수 있습니다.

포지션 매칭

포지션 매칭은 ^와 $(을)를 사용하여 문자열의 시작이나 끝을 검색합니다. 패턴 속성을 "^VBScript"로 설정할 경우, "VBScript is cool."에는 일치하지만, "I like VBScript."에는 일치하지 않습니다.

기호 기능
^ 문자열의 시작만 비교합니다

"^A"는 "An A+ for Anita."의 첫번째 "A"를 비교합니다.
$ 문자열의 끝을 비교합니다.

"t$"는 "A cat in the hat"의 마지막 "t"를 비교합니다.
? 임의의 워드 영역을 비교합니다

"lyB"는 "possibly tomorrow."의 "ly"를 비교합니다
B Matches any non-word boundary




리터럴

리터럴은 영숫자 문자, ASCII, 8진수 문자, 16진수 문자, UNICODE, 또는 특수 구분 문자 등을 모두 총칭하는 말입니다. 특별한 의미를 갖고 있는 몇몇 문자는 구분해야 합니다. 이들 특수 문자를 비교하려면, 정규 표현식을 문자 앞에 를 사용해야 합니다.

기호 기능
영숫자 영문자와 숫자를 비교합니다.

새로운 라인을 비교합니다
f 용지 공급을 비교합니다

캐리지 리턴을 비교합니다.
가로 탭을 비교합니다.
v 수평 탭을 비교합니다.
? ?(을)를 비교합니다.
* *(을)를 비교합니다.
+ +(을)를 비교합니다.
. . (을)를 비교합니다.
| |(을)를 비교합니다.
{ {(을)를 비교합니다.
} }(을)를 비교합니다.
\ (을)를 비교합니다.
[ [(을)를 비교합니다.
] ] (을)를 비교합니다.
( ((을)를 비교합니다.
) ) (을)를 비교합니다.
xxx 8진수 xxx로 표시된 ASCII 문자를 비교합니다.

"50"은 "(" 또는 chr (40) (을)를 비교합니다.
xdd 16진수 dd로 표시된 ASCII 문자를 비교합니다.

"x28"은 "(" 또는 chr (40) (을)를 비교합니다.
uxxxx UNICODE xxxx로 표시된 ASCII 문자를 비교합니다.

"u00A3"은 "£"를 비교합니다.

문자 클래스

문자 클래스를 사용하면 괄호 [] 안에 식을 삽입하여 사용자에 의해 정의된 그룹을 만들 수 있습니다. 문자 클래스의 문자들을 제외한 나머지 문자들을 사용하려면 [] 안에 ^(을)를 첫번째 문자로 삽입해야 합니다. 또한, 문자의 범위를 지정할 때는 대시를 사용합니다. 예를 들어, 정규 표현식 "[^a-zA-Z0-9]"(은)는 영문자와 숫자를 제외한 모든 문자를 비교합니다. 추가로 구분 문자와 리터럴로 묶인 문자셋도 있습니다.


기호 기능
[xyz] 문자셋 안에 포함되어 있는 임의의 한 문자를 비교합니다.

"[a-e]" (은)는 "basketball" 안의 "b"를 비교합니다.
[^xyz] 문자 셋 안에 포함되어 있지 않은 임의의 한 문자를 비교합니다.

"[^a-e]"는 "basketball" 안의 "s"를 비교합니다.
.
을 제외한 임의의 문자를 비교합니다.
w 임의의 워드 문자를 비교합니다.
[a- zA-Z_0-9]와 동일함.
W 워드 문자를 제외한 임의의 문자를 비교합니다.
[^a-zA-Z_0-9]와 동일함.
d 임의의 숫자를 비교합니다. [0-9].
D 숫자를 제외한 임의의 문자를 비교합니다.
[^0-9]와 동일함.
s 임의의 공백 문자를 비교합니다.
[
vf]와 동일함.
S 공백 문자가 아닌 임의의 문자를 비교합니다.
[^
vf]와 동일함.

반복

반복 매칭을 사용하면 정규 표현식 안에 있는 특정 절에 대한 검색을 여러 번 수행할 수 있습니다. 반복 매칭에서는 어떤 요소가 정규 표현식 안에서 몇 번 반복될 것인지를 지정할 수 있습니다.

기호 기능
{x} {x} 정규 표현식을 x번 비교합니다.

"d{5}"는 5개의 숫자를 비교합니다.
(x,} 정규 표현식을 x번 이상 비교합니다.

"s{2,}"는 최소한 두 개의 공백 문자를 비교합니다
{x,y} 정규 표현식을 x부터 y번까지 비교합니다.

"d{2,3}"는 2개 이상 3개 미만의 숫자를 비교합니다. .
? 0번 또는 한 번 비교합니다. {0,1}와 동일함.

"as?b"는 "ab" 또는 "a b"를 비교합니다.
* 0번 이상 비교합니다. {0,}와 동일함.
+ 한번 이상 비교합니다.{1,}과 동일함.


교체와 그룹핑

교체와 그룹핑은 보다 복잡한 정규 표현식을 만들 때 사용합니다. 교체와 그룹핑 기술은 정규 표현식 안에 복잡한 절을 만들고, 보다 많은 융통성과 제어 능력을 제공합니다.

기호 기능
() 절을 그룹핑하여 절을 만듭니다. 중첩하여 사용할 수도 있습니다.

"(ab)?(c)"는 "abc" 또는 "c"를 비교합니다.
| 교체는 여러 절을 하나의 정규 표현식으로 조합한 다음 개별적인 절을 비교합니다.

"(ab)|(cd)|(ef)"는 "ab" 또는 "cd" 또는 "ef"를 비교합니다.

역방향 참조

프로그래머는 역방향 참조를 통해 정규 표현식의 일부를 다시 참조할 수 있습니다. 그 방법은 괄호와 백슬레시() 뒤에 한 개의 숫자를 사용하는 것입니다. 첫 번째 괄호 절은 1로 참조되고 두 번째 괄호 절은 2로 참조되는 식입니다.

기호 기능
()
왼쪽 괄호에 있는 표현식을 n번 반복해서 문장을 비교합니다.

"(w+)s+1"는 "hubba hubba" 같이, 한 열 안에서 두 번 나타나는 임의의 워드를 비교합니다.."

예제로 확인하기!
이 예제는 지금까지 설명한 것을 적용한 것으로, 정규 표현식을 이용하여 유효한 입력 값이 입력되어 있는지 검사하는 간단한 응용 프로그램입니다. 사용자가 유효한 값을 입력할 때까지 사용자에게 입력을 요구하는 프롬프트가 반복적으로 나타납니다. 먼저 초기 패턴을 자세히 설명하겠습니다.

"^s*(($s?)|(£s?))?((d+(.(dd)?)?)|(.dd))s*(UK|GBP|GB|USA|US|USD)?)s*$"

"^s*…" 와 "…s*$" - 앞과 뒤에 몇 개의 공백 문자든지 올 수 있음을 나타내며, 입력은 반드시 라인 자체 위에 있어야 합니다.
"(($s?)|(?s?))?" - 옵션 공백 앞에 오는 옵션 $ 또는 £ 기호를 나타냅니다..
"((d+(.(dd)?)?)|(.dd))" - 생략 가능한 십진수 소수점 2자리 또는 십진수 소수점 2 자리수 앞에 오는 한 자리 이상의 숫자를 찾습니다. 이 말은 6., 23.33, .88와 같은 숫자는 사용 가능하나 5.5는 사용할 수 없음을 의미합니다.
"s*(UK|GBP|GB|USA|US|USD)?" - 문자열에 대하여 생략 및 사용이 가능하고 인수 앞에서 유효한 공백 문자의 수를 의미합니다.
본 예제의 경우, 정규 표현식은 사용자의 US 달러 또는 영국 파운드 입력 여부를 결정하는 데 사용됩니다. 필자는 £, UK, GBP, 또는 GB 문자열을 검색하고 있습니다. 정규 표현식 결과가 참이면 사용자는 영국 파운드 단위의 액수를 입력한 것이라고 보면 됩니다. 그렇지 않다면 USD 통화를 사용한 것이겠지요.

이 코드를 사용하려면 코드를 CurrencyEx.vbs로 저장하고 Windows Script Host를 이용해 코드를 실행시킨 다음 VB에 복사하거나(이 경우, Microsoft VBScript 정규 표현식에 참조를 추가할 필요가 있음) HTML 파일에 코드를 포함시킵니다.

Sub CurrencyEx
Dim inputstr, re, amt
Set re = new regexp 'Create the RegExp object

'Ask the user for the appropriate information
inputstr = inputbox("I will help you convert USA and CAN currency. Please enter the amount to convert:")
'Check to see if the input string is a valid one.
re.Pattern = "^s*(($s?)|(£s?))?((d+(.(dd)?)?)|(.dd))s*(UK|GBP|GB|USA|US|USD)?)s*$"
re.IgnoreCase = true
do while re.Test(inputstr) <> true
'Prompt for another input if inputstr is not valid
inputstr = inputbox("I will help you convert USA and GBP currency. Please enter the amount to(USD or GBP):")

loop
'Determine if we are going from GBP->US or USA->GBP
re.Pattern = "£|UK|GBP|GB"
if re.Test(inputstr) then
'The user wants to go from GBP->USD

re.Pattern = "[a-z$£ ]"
re.Global = True
amt = re.Replace(inputstr, "")
amt = amt * 1.6368
amt = cdbl(cint(amt * 100) / 100)
amt = "$" & amt
else
'The user wants to go from USD->GBP

re.Pattern = "[a-z$£ ]"
re.Global = True
amt = re.Replace(inputstr, "")
amt = amt * 0.609
amt = cdbl(cint(amt * 100) / 100)
amt = "£" & amt
end if

msgbox ("Your amount of: " & vbTab & inputstr & vbCrLf & "is equal to: " & vbTab & amt)
End sub


더욱 강력한 파워를!
Visual Basic 개발자들이 정규 표현식을 사용할 수 있도록 VBScript 정규 표현식 엔진은 COM 개체로 구현되어 왔습니다. 이 경우, 정규 표현식은 보다 강력한 힘을 발휘하게 되는데 즉, Visual Basic 또는 C와 같은 VBScript 외의 다양한 소스로부터 호출이 가능하기 때문입니다. 예컨대, 필자는 Outlook(R) 97, Outlook 98 또는 Outlook 2000의 접속 목록을 통해 내용을 추적하고 특정 도시에 사는 접속자 이름을 반환하는 작은 Visual Basic 응용 프로그램을 만든 경험이 있습니다.

이 프로그램은 매우 간단합니다. 먼저 사용자는 검색할 대상 도시명을 입력하고, 구분 표시에는 쉼표를 사용합니다. 그런 다음, Outlook에 작성할 새 접속 폴더의 이름을 입력합니다. 각 접속이 일치하면 이 내용은 새로 작성된 접속 폴더에 복사됩니다.

Microsoft VBScript 정규 표현식 개체 라이브러리에 참조를 추가할 경우 몇 가지 유용한 조기 바인딩 기능(early binding)을 사용할 수 있습니다. 이 조기 바인딩 개체는 몇 가지 이점을 제공하는데 즉, 속도가 빠르고 코딩 프로그램 사용이 간편하다는 점입니다. "new RegExp"가 즉시 사용되므로 사용자는 개체에 참조를 추가하고 VBScript코드를 오려내어 VB에 그대로 붙일 수 있습니다.

이러한 이유로 필자 또한 정규 표현식과 동일한 방법을 사용하여 Outlook 9.0 개체 라이브러리를 참조한 적이 있습니다. 물론, 여러분은 여전히 CreateObject() (을)를 사용하여 COM 호출을 생성시킬 수도 있으나 상기 방법을 더 간편하게 사용할 수 있을 것입니다. 이 개체들을 작성한 후 간단한 코드를 사용하여 도시명과 일치하는 폴더와 트리를 액세스할 수 있습니다. 본인은 2개의 모음 개체를 가지는 작은 도움 함수 compareCollectionObjects(x,y)(을)를 사용/비교하여 일치 여부를 확인합니다.

이 프로그램을 사용하려면 단순히 코드를 VB(참조 추가에 필요함)에 복사한 다음 FindCityContacts() 함수를 호출하면 됩니다. .


Sub FindCityContacts()

Dim strTemp
Dim index
Dim citySearch
Dim myNameSpace, myContacts, newCityContacts, newCityContactsName
Dim contact
Dim newContact

'Set the early binding objects
Dim re as New RegExp
Dim myApp as New Outlook.Application

re.Global = True
re.IgnoreCase = True

citySearch = InputBox("Please enter the cities of your search, separated by commas.")
newCityContactsName = InputBox("Please enter the new contact folder name")

'Set some of the objects and create the new Contacts folder
Set myNameSpace = myApp.GetNamespace("MAPI")
'olFolderContacts = 10
Set myContacts = myNameSpace.GetDefaultFolder(10)
Set newCityContacts = myContacts.Folders.Add(newCityContactsName)

'Set cities, using regular expressions to contain the city names
re.Pattern = "[^,]+"
Set cities = re.Execute(citySearch)
For Each city In cities

'Set citytokens to be the individual tokens in the city name
'Then we compare them to the address tokens in each contact
re.Pattern = "[^ ]+"
Set citytokens = re.Execute(city)

For i = 1 to myContacts.Items.Count
re.Pattern = "[^ ]+"
Set contact = myContacts.Items.Item(i)

Set HomeAddressCityTokens = re.Execute(contact.HomeAddressCity)
If compareCollectionObjects(HomeAddressCityTokens, citytokens) = 1 Then

Set newContact = contact.Copy
newContact.Move newCityContacts
End If

Set OtherAddressCityTokens = re.Execute(contact.OtherAddressCity)
If compareCollectionObjects(OtherAddressCityTokens, citytokens) = 1 Then
Set newContact = contact.Copy
newContact.Move newCityContacts
End If

Set BusinessAddressCityTokens = re.Execute(contact.BusinessAddressCity)
If compareCollectionObjects(BusinessAddressCityTokens, citytokens) = 1 Then
Set newContact = contact.Copy
newContact.Move newCityContacts
End If
Next
Next

MsgBox "done"

End Sub

'This function is provided as a helper-function
' to compare two collection objects.
Function compareCollectionObjects(x, y)

Dim index
Dim flag
flag = 1

If x.Count <> y.Count Then
flag = 0
Else
index = x.Count

For i = 0 To (index - 1)
If StrComp(x.Item(i), y.Item(i), 1) Then
flag = 0
End If
Next
End If

compareCollectionObjects = flag

End Function


넘치는 정보!
앞에서 보았듯이, Microsoft는 정규 표현식(버전 5.0)을 이용하여 VBSscript를 강화시키는데, 이것은 VBScript와 Jscript 비교에서 가장 중요한 부분이었습니다. 스크립팅 엔진 버전 5.0에서 우리는 VBScript의 기능을 향상시키는 데 특히 비중을 두었습니다. 이제 여러분은 정규 표현식을 추가시킴으로써 데이터를 보다 확실하게 관리하고 그 효과를 높일 수 있게 되었으며, 클라이언트와 서버에서 보다 강력한 웹 응용 프로그램을 만들 수 있게 되었습니다.

출처 : http://nurikkun.pe.kr/tt/entry/JavaScript-정규식?TSSESSION=28333ab273a6409833611c49221f841d
Posted by heresyrt
이전페이지 1 2 3 다음페이지
위로

사이드바 열기