자바를 이용한 패킷캡처하기
안녕하세요 패킷캡처에 대해 공부를 하고있는 학생입니다.
와이어샤크와 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;
}
}
댓글 달기