자바를 이용한 패킷캡처하기

gkdms02의 이미지

안녕하세요 패킷캡처에 대해 공부를 하고있는 학생입니다.
와이어샤크와 jpcap을 이용하면서 패킷분석및 캡처를 공부를 하고 있는데요
공부를 하던중 오픈소스를 이용해 쫌 더 확실히 분류 할수 있는 캡처를 하려고 하는데요
패킷이 오면 출발지와 도착지를 표시 하는것까지는 소스를 짰는데 그 이후에 프로토콜 분류를 하는데 있어서
애를 먹어 이렇게 소스를 올려봅니다 .

제가 만든 주소는 대략 이러합니다.

import java.net.*;
import java.io.*;
import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.packet.*;
import java.io.*;
import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.packet.*;

public class Main
{

JpcapCaptor captor;
NetworkInterface[] list;
String str,info;
int x, nChoice;

int nCountPacket = 0;

public static void main(String args[]) {
new Main();
}

public Main()
{

list = JpcapCaptor.getDeviceList();//Device리스트를 list에 저장
System.out.println("사용 가능한 인터페이스 : ");

for(x=0; x System.out.println(x+" -> "+list[x].description); //list에 저장된 device들 출력
}

System.out.println("-------------------------");
nChoice = Integer.parseInt(getInput("인터페이스 선택 (0,1..): "));//선택
System.out.println(""+list[nChoice].description+" 으로 부터 패킷 받아오는 중");//선택된 device 출력
System.out.println("-------------------------");

NetworkInterface[] devices = JpcapCaptor.getDeviceList();
for (int i = 0; i < devices.length; i++) {
System.out.println((i+1)+": "+devices[i].name + "(" + devices[i].description+")");
System.out.println(" datalink: "+devices[i].datalink_name + "(" + devices[i].datalink_description+")");
System.out.print(" MAC address:");
for (byte b : devices[i].mac_address) {
System.out.print(Integer.toHexString(b&0xff) + ":");

}
System.out.println();
for (NetworkInterfaceAddress a : devices[i].addresses) {

System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);

}
System.out.println("");
}


/*Setup device listener */

try {
//선택된 device를 captor에 저장. (선택된것, 한번에 받아올양, 모든 회선을 잡을지 여부, 타임아웃)
captor=JpcapCaptor.openDevice(list[nChoice], 65535, false, 20);
/* listen for TCP/IP only */
captor.setFilter("ip and tcp", true);//tcp/ip만 걸러내도록 필터적용
} catch(IOException ioe) { ioe.printStackTrace(); }


/* start listening for packets */
while (true) {
Packet info = captor.getPacket();//패킷얻어서

if(info != null){//잘 얻었으면
String sData = getPacketText(info); //패킷을 String으로 가져와서
System.out.print(sData);//출력
}
}
}



/* get user input 사용자 입력 받는함수*/
public static String getInput(String q)
{
String input = "";
System.out.print(q);
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in));
try {
input = bufferedreader.readLine();
} catch(IOException ioexception) { }
return input;
}


/* return packet data in true text */
String getPacketText(Packet pack)
{

int i=0,j=0;
//패킷데이터 받을 bytes를 생성후 bytes에 집어넣는다.
byte[] bytes=new byte[pack.data.length];
System.arraycopy(pack.data, 0, bytes, 0, pack.data.length);

String sPackInfo = "";
if( pack.data.length > 0){ //패킷 길이가 0보다 크면
sPackInfo = "\n출발지:" + ((IPPacket)pack).src_ip + "" + " 도착지점:" + ( (IPPacket)pack).dst_ip+"\n";
//문자열에 SRC, DST넣기
sPackInfo += "" + ShowHex(bytes.length, bytes) ;
//문자열에 Hex코드도 넣기
}


return sPackInfo;//리턴
}


// Hex 출력 이 부분은 hex부분이라 자세하게 설명이 힘들꺼 같네요..
private String ShowHex(int nSize, byte[] pData)
{
final int DISPLAY_COUNT = 16; //보일 개수
final int MAX_SIZE = 1024 * 15; //최대 크기

String msg = "";
String sTmp = "";
String sTmp2 = "";
String sLineNum = "";

int nLineNum = 0;

msg = "0000:";

if(nSize > MAX_SIZE) nSize = MAX_SIZE;

for(int i = 1; i < nSize + 1; i++){
sTmp = sTmp.format("%02X ", pData[ i - 1 ] );
if(( pData[ i - 1] < 127) && ( pData[ i - 1] > 32)){
sTmp2 += sTmp2.format("%c", pData[ i - 1 ] );

} else {
sTmp2 += ".";
}

if(i % DISPLAY_COUNT == 0 && i != 1){
msg += sTmp;

msg += " ";
msg += sTmp2;

msg += "\n";

sTmp2 = "";

msg += sLineNum.format("%04X:", nLineNum += DISPLAY_COUNT);

} else if(i == nSize && i % DISPLAY_COUNT != 0 ){
int nEmtSpace = DISPLAY_COUNT - (i % DISPLAY_COUNT);
for(int j = 0; j < nEmtSpace; j++){
sTmp += " ";
}
msg += sTmp;
msg += " ";
msg += sTmp2;
msg += "";

} else {
msg += sTmp;
}
}

if ( nSize == 0 ) msg = "";
return msg;
}

}

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.