<?php
// Fonction pour pinger une IP
function ping($ip) {
    exec("ping -n 1 -W 1 $ip 2>/dev/null", $output, $status);
    return $status === 0;
}

// Fonction pour récupérer l'adresse MAC via ARP
function getMac($ip) {
    exec("arp -n $ip", $output);
    if (isset($output[1])) {
        $parts = preg_split('/\s+/', $output[1]);
        return $parts[2] ?? 'Inconnu';
    }
    return 'Inconnu';
}

// Si formulaire soumis
$results = [];
if (isset($_POST['subnet'])) {
    $subnet = $_POST['subnet'];
    $getMac = isset($_POST['with_mac']);
    for ($i = 1; $i <= 254; $i++) {
        $ip = "$subnet.$i";
        if (ping($ip)) {
            $mac = $getMac ? getMac($ip) : 'Non récupéré';
            $results[] = ['ip' => $ip, 'mac' => $mac];
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Scanner IP Réseau Local</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Scanner d'Adresses IP sur le Réseau Local</h1>
    <form method="post">
        <label>Sous-réseau (ex : 192.168.1):</label>
        <input type="text" name="subnet" required placeholder="192.168.1">
        <br>
        <label>
            <input type="checkbox" name="with_mac">
            Récupérer les adresses MAC
        </label>
        <br><br>
        <button type="submit">Lancer le scan</button>
    </form>

    <?php if (!empty($results)): ?>
        <h2>Résultats du Scan</h2>
        <table>
            <thead>
                <tr>
                    <th>Adresse IP</th>
                    <th>Adresse MAC</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($results as $device): ?>
                    <tr>
                        <td><?= htmlspecialchars($device['ip']) ?></td>
                        <td><?= htmlspecialchars($device['mac']) ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</body>
</html>
