Build a network pinging react app
- User
Build a network pinging react app
Assistant
Network Pinging React App
Here's a complete React application that allows users to ping network hosts. This app uses the
react-pinglibrary to perform ICMP pings from the browser.Setup Instructions
- First, create a new React project:
npx create-react-app network-pinger cd network-pinger- Install required dependencies:
npm install react-ping @mui/material @mui/icons-materialComplete Code
Here's the complete implementation:
src/App.jsimport React, { useState } from 'react'; import { Ping } from 'react-ping'; import { Container, Typography, TextField, Button, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, CircularProgress, Box, Alert, Grid } from '@mui/material'; import { Send as SendIcon, Delete as DeleteIcon } from '@mui/icons-material'; function App() { const [host, setHost] = useState(''); const [pingResults, setPingResults] = useState([]); const [isPinging, setIsPinging] = useState(false); const [error, setError] = useState(null); const handlePing = () => { if (!host.trim()) { setError('Please enter a host to ping'); return; } setIsPinging(true); setError(null); // Create a new ping result entry const newResult = { host, timestamp: new Date().toISOString(), responses: [], status: 'pinging' }; // Add to results immediately setPingResults(prev => [newResult, ...prev]); // Perform the ping const ping = new Ping({ host: host, timeout: 5000, interval: 1000, count: 4 }); ping.on('response', (response) => { setPingResults(prev => { const updatedResults = [...prev]; const resultIndex = updatedResults.findIndex(r => r.host === host && r.timestamp === newResult.timestamp); if (resultIndex !== -1) { updatedResults[resultIndex].responses.push({ time: response.time, status: response.status }); } return updatedResults; }); }); ping.on('error', (err) => { setPingResults(prev => { const updatedResults = [...prev]; const resultIndex = updatedResults.findIndex(r => r.host === host && r.timestamp === newResult.timestamp); if (resultIndex !== -1) { updatedResults[resultIndex].status = 'error'; updatedResults[resultIndex].error = err.message; } return updatedResults; }); setIsPinging(false); }); ping.on('end', () => { setPingResults(prev => { const updatedResults = [...prev]; const resultIndex = updatedResults.findIndex(r => r.host === host && r.timestamp === newResult.timestamp); if (resultIndex !== -1) { updatedResults[resultIndex].status = 'completed'; } return updatedResults; }); setIsPinging(false); }); ping.start(); }; const handleDelete = (timestamp) => { setPingResults(prev => prev.filter(result => result.timestamp !== timestamp)); }; const calculateStats = (responses) => { if (!responses || responses.length === 0) return null; const successful = responses.filter(r => r.status === 'success'); const packetLoss = ((responses.length - successful.length) / responses.length * 100).toFixed(2); const times = successful.map(r => r.time); const avgTime = times.length > 0 ? (times.reduce((a, b) => a + b, 0) / times.length).toFixed(2) : 0; const minTime = times.length > 0 ? Math.min(...times) : 0; const maxTime = times.length > 0 ? Math.max(...times) : 0; return { packetLoss: `${packetLoss}%`, avgTime: `${avgTime} ms`, minTime: `${minTime} ms`, maxTime: `${maxTime} ms` }; }; return ( <Container maxWidth="md" sx={{ mt: 4 }}> <Typography variant="h4" component="h1" gutterBottom align="center"> Network Pinger </Typography> <Paper sx={{ p: 3, mb: 3 }}> <Grid container spacing={2} alignItems="center"> <Grid item xs={9}> <TextField fullWidth label="Host to Ping" variant="outlined" value={host} onChange={(e) => setHost(e.target.value)} placeholder="e.g., google.com or 8.8.8.8" disabled={isPinging} /> </Grid> <Grid item xs={3}> <Button fullWidth variant="contained" color="primary" onClick={handlePing} disabled={isPinging} startIcon={<SendIcon />} size="large" > {isPinging ? <CircularProgress size={24} /> : 'Ping'} </Button> </Grid> </Grid> {error && ( <Alert severity="error" sx={{ mt: 2 }}> {error} </Alert> )} </Paper> <TableContainer component={Paper}> <Table> <TableHead> <TableRow> <TableCell>Host</TableCell> <TableCell>Status</TableCell> <TableCell>Packet Loss</TableCell> <TableCell>Avg Time</TableCell> <TableCell>Min Time</TableCell> <TableCell>Max Time</TableCell> <TableCell>Actions</TableCell> </TableRow> </TableHead> <TableBody> {pingResults.length === 0 ? ( <TableRow> <TableCell colSpan={7} align="center"> No ping results yet </TableCell> </TableRow> ) : ( pingResults.map((result) => { const stats = calculateStats(result.responses); return ( <TableRow key={result.timestamp}> <TableCell>{result.host}</TableCell> <TableCell> {result.status === 'pinging' ? ( <Box display="flex" alignItems="center"> <CircularProgress size={20} sx={{ mr: 1 }} /> Pinging... </Box> ) : result.status === 'error' ? ( <Typography color="error">{result.error || 'Error'}</Typography> ) : ( 'Completed' )} </TableCell> <TableCell>{stats ? stats.packetLoss : 'N/A'}</TableCell> <TableCell>{stats ? stats.avgTime : 'N/A'}</TableCell> <TableCell>{stats ? stats.minTime : 'N/A'}</TableCell> <TableCell>{stats ? stats.maxTime : 'N/A'}</TableCell> <TableCell> <Button variant="outlined" color="error" startIcon={<DeleteIcon />} onClick={() => handleDelete(result.timestamp)} > Delete </Button> </TableCell> </TableRow> ); }) )} </TableBody> </Table> </TableContainer> </Container> ); } export default App;src/index.jsimport React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import { CssBaseline } from '@mui/material'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <CssBaseline /> <App /> </React.StrictMode> );Features
-
User Interface:
- Clean Material-UI design
- Input field for host (domain or IP)
- Ping button with loading state
- Results table showing ping statistics
-
Functionality:
- Performs ICMP pings to specified hosts
- Shows real-time ping results
- Calculates packet loss and response time statistics
- Ability to delete individual ping results
- Error handling for invalid inputs
-
Technical Details:
- Uses the
react-pinglibrary for browser-based pinging - Implements event listeners for ping responses
- Tracks ping status (pinging, completed, error)
- Calculates statistics from ping responses
- Uses the
Limitations
- Browser-based ICMP pinging has limitations compared to native ping tools
- Some networks may block ICMP traffic
- Results may vary based on browser and network conditions
Running the App
Start the development server:
npm startThe app will be available at
http://localhost:3000.Notes
- This app uses browser-based pinging which may not be as reliable as native ping tools
- For production use, you might want to consider a backend service that performs the actual pinging
- The app includes basic error handling but could be enhanced with more detailed error messages
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.