0% found this document useful (0 votes)
23 views6 pages

Pojet RESEAU

The document is a Java program that implements a graphical user interface (GUI) for capturing and analyzing network packets using the Pcap4j library. It allows users to select network interfaces, apply filters, and view captured packets in a table format, along with detailed information about each packet. The application includes functionalities to start and stop packet capture, refresh network interfaces, and display packet details upon selection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views6 pages

Pojet RESEAU

The document is a Java program that implements a graphical user interface (GUI) for capturing and analyzing network packets using the Pcap4j library. It allows users to select network interfaces, apply filters, and view captured packets in a table format, along with detailed information about each packet. The application includes functionalities to start and stop packet capture, refresh network interfaces, and display packet details upon selection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

package com.mycompany.

packetcapturegui;

import org.pcap4j.core.*;
import org.pcap4j.core.PcapNetworkInterface.PromiscuousMode;
import org.pcap4j.packet.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.*;

public class PacketCaptureGUI extends JFrame {

private DefaultTableModel tableModel;


private JTable packetTable;
private JComboBox<PcapNetworkInterface> interfaceComboBox;
private JComboBox<String> filterComboBox;
private JButton startButton;
private JButton stopButton;
private PcapHandle handle;
private ExecutorService executor;
private JLabel statusLabel;
private JTextArea packetDetailsArea;

public PacketCaptureGUI() {
super("Analyseur de Trames Réseau");
initializeUI();
loadNetworkInterfaces();
}

private void initializeUI() {


setSize(1200, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Panel de configuration
JPanel configPanel = new JPanel(new GridLayout(2, 1));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

// Sélection de l'interface
interfaceComboBox = new JComboBox<>();
interfaceComboBox.setPreferredSize(new Dimension(800, 25));
JButton refreshButton = new JButton("Rafraîchir");
refreshButton.addActionListener(e -> loadNetworkInterfaces());

// Sélection du filtre
filterComboBox = new JComboBox<>(new String[]{"TCP et UDP", "TCP
uniquement", "UDP uniquement"});
filterComboBox.setPreferredSize(new Dimension(150, 25));

// Boutons de contrôle
startButton = new JButton("Démarrer la capture");
startButton.setPreferredSize(new Dimension(150, 30));
stopButton = new JButton("Arrêter la capture");
stopButton.setPreferredSize(new Dimension(150, 30));
stopButton.setEnabled(false);
// Barre de statut
statusLabel = new JLabel("Prêt");
statusLabel.setBorder(BorderFactory.createEtchedBorder());

// Ajout des composants


topPanel.add(new JLabel("Interface réseau: "));
topPanel.add(interfaceComboBox);
topPanel.add(refreshButton);
topPanel.add(new JLabel("Filtre: "));
topPanel.add(filterComboBox);

bottomPanel.add(startButton);
bottomPanel.add(stopButton);
bottomPanel.add(statusLabel);

configPanel.add(topPanel);
configPanel.add(bottomPanel);

// Configuration du tableau
String[] columns = {"Heure", "Protocole", "IP Source", "Port Source", "IP
Destination", "Port Destination", "Taille (bytes)"};
tableModel = new DefaultTableModel(columns, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};

packetTable = new JTable(tableModel);


packetTable.setAutoCreateRowSorter(true);
JScrollPane tableScrollPane = new JScrollPane(packetTable);
tableScrollPane.setPreferredSize(new Dimension(1150, 400));

// Zone de détails des paquets


packetDetailsArea = new JTextArea();
packetDetailsArea.setEditable(false);
packetDetailsArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
JScrollPane detailsScrollPane = new JScrollPane(packetDetailsArea);
detailsScrollPane.setPreferredSize(new Dimension(1150, 90));

// Panel principal pour les résultats


JPanel resultsPanel = new JPanel(new BorderLayout());
resultsPanel.add(tableScrollPane, BorderLayout.NORTH);
resultsPanel.add(detailsScrollPane, BorderLayout.CENTER);

// Ajout des composants à la fenêtre


add(configPanel, BorderLayout.NORTH);
add(resultsPanel, BorderLayout.CENTER);

// Gestion des événements


startButton.addActionListener(e -> startCapture());
stopButton.addActionListener(e -> stopCapture());
packetTable.getSelectionModel().addListSelectionListener(e ->
showPacketDetails());

setLocationRelativeTo(null);
pack();
}
private void loadNetworkInterfaces() {
interfaceComboBox.removeAllItems();
try {
List<PcapNetworkInterface> devices = Pcaps.findAllDevs();
if (devices.isEmpty()) {
statusLabel.setText("Aucune interface réseau trouvée!");
return;
}

for (PcapNetworkInterface device : devices) {


interfaceComboBox.addItem(device);
}
statusLabel.setText(devices.size() + " interfaces trouvées");
} catch (PcapNativeException e) {
statusLabel.setText("Erreur: " + e.getMessage());
JOptionPane.showMessageDialog(this,
"Erreur lors de la recherche des interfaces: " + e.getMessage(),
"Erreur", JOptionPane.ERROR_MESSAGE);
}
}

private void startCapture() {


if (interfaceComboBox.getSelectedItem() == null) {
JOptionPane.showMessageDialog(this,
"Veuillez sélectionner une interface réseau",
"Erreur", JOptionPane.ERROR_MESSAGE);
return;
}

startButton.setEnabled(false);
stopButton.setEnabled(true);
interfaceComboBox.setEnabled(false);
filterComboBox.setEnabled(false);
statusLabel.setText("Capture en cours...");
packetDetailsArea.setText("");

try {
PcapNetworkInterface device = (PcapNetworkInterface)
interfaceComboBox.getSelectedItem();
String filter;
String selectedFilter = filterComboBox.getSelectedItem().toString();
if (null == selectedFilter) {
filter = "tcp or udp";
} else switch (selectedFilter) {
case "TCP uniquement":
filter = "tcp";
break;
case "UDP uniquement":
filter = "udp";
break;
default:
filter = "tcp or udp";
break;
}

handle = device.openLive(65536, PromiscuousMode.PROMISCUOUS, 10);


handle.setFilter(filter, BpfProgram.BpfCompileMode.OPTIMIZE);

tableModel.setRowCount(0);
executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
try {
PacketListener listener = this::processPacket;
handle.loop(-1, listener);
} catch (InterruptedException | NotOpenException |
PcapNativeException e) {
if (!e.getMessage().contains("Interrupted")) {
SwingUtilities.invokeLater(() -> {
statusLabel.setText("Erreur: " + e.getMessage());
JOptionPane.showMessageDialog(this,
"Erreur pendant la capture: " + e.getMessage(),
"Erreur", JOptionPane.ERROR_MESSAGE);
});
}
}
});
} catch (NotOpenException | PcapNativeException e) {
statusLabel.setText("Erreur de démarrage");
JOptionPane.showMessageDialog(this,
"Erreur de démarrage: " + e.getMessage(),
"Erreur", JOptionPane.ERROR_MESSAGE);
stopCapture();
}
}

private void processPacket(Packet packet) {


String protocol = "";
String srcIp = "";
String dstIp = "";
String srcPort = "";
String dstPort = "";
int length = packet.length();

IpPacket ipPacket = packet.get(IpPacket.class);


if (ipPacket != null) {
srcIp = ipPacket.getHeader().getSrcAddr().getHostAddress();
dstIp = ipPacket.getHeader().getDstAddr().getHostAddress();
}

if (packet.contains(TcpPacket.class)) {
TcpPacket tcp = packet.get(TcpPacket.class);
protocol = "TCP";
srcPort = String.valueOf(tcp.getHeader().getSrcPort().value());
dstPort = String.valueOf(tcp.getHeader().getDstPort().value());
} else if (packet.contains(UdpPacket.class)) {
UdpPacket udp = packet.get(UdpPacket.class);
protocol = "UDP";
srcPort = String.valueOf(udp.getHeader().getSrcPort().value());
dstPort = String.valueOf(udp.getHeader().getDstPort().value());
}

if (!protocol.isEmpty()) {
Object[] rowData = {
LocalTime.now().withNano(0).toString(),
protocol,
srcIp,
srcPort,
dstIp,
dstPort,
length
};

SwingUtilities.invokeLater(() -> {
tableModel.addRow(rowData);
scrollToLastRow();
statusLabel.setText("Capture en cours : " +
tableModel.getRowCount() + " paquets capturés");
});
}
}

private void showPacketDetails() {


int selectedRow = packetTable.getSelectedRow();
if (selectedRow >= 0) {
String protocol = (String) tableModel.getValueAt(selectedRow, 1);
String srcIp = (String) tableModel.getValueAt(selectedRow, 2);
String srcPort = (String) tableModel.getValueAt(selectedRow, 3);
String dstIp = (String) tableModel.getValueAt(selectedRow, 4);
String dstPort = (String) tableModel.getValueAt(selectedRow, 5);

StringBuilder details = new StringBuilder();


details.append("=== Détails du paquet ===\n");
details.append("Protocole: ").append(protocol).append("\n");
details.append("Source:
").append(srcIp).append(":").append(srcPort).append("\n");
details.append("Destination:
").append(dstIp).append(":").append(dstPort).append("\n");

packetDetailsArea.setText(details.toString());
}
}

private void scrollToLastRow() {


int lastRow = tableModel.getRowCount() - 1;
if (lastRow >= 0) {
packetTable.scrollRectToVisible(packetTable.getCellRect(lastRow, 0,
true));
}
}

private void stopCapture() {


try {
if (handle != null && handle.isOpen()) {
handle.breakLoop();
handle.close();
}
} catch (NotOpenException e) {
// Ignorer
}

if (executor != null) {
executor.shutdownNow();
}

startButton.setEnabled(true);
stopButton.setEnabled(false);
interfaceComboBox.setEnabled(true);
filterComboBox.setEnabled(true);
statusLabel.setText("Capture arrêtée : " + tableModel.getRowCount() + "
paquets capturés");
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new PacketCaptureGUI().setVisible(true);
} catch (ClassNotFoundException | IllegalAccessException |
InstantiationException | UnsupportedLookAndFeelException e) {
JOptionPane.showMessageDialog(null,
"Erreur lors du démarrage: " + e.getMessage(),
"Erreur", JOptionPane.ERROR_MESSAGE);
}
});
}
}

You might also like