or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

automation.mdconfig-utilities.mdcore-packet-system.mdindex.mdpacket-analysis.mdprotocol-layers.mdsend-receive.md

config-utilities.mddocs/

0

# Configuration and Utilities

1

2

Global configuration management, utility functions for data conversion, validation, file operations, and platform-specific functionality that supports Scapy's core operations.

3

4

## Capabilities

5

6

### Global Configuration

7

8

Scapy's global configuration system that controls behavior, protocols, and platform-specific settings.

9

10

```python { .api }

11

class Conf:

12

"""

13

Global configuration object for Scapy settings.

14

"""

15

def configure(self, **kwargs) -> None:

16

"""

17

Configure multiple settings at once.

18

19

Parameters:

20

- **kwargs: Configuration key-value pairs

21

"""

22

23

# Network interface settings

24

iface: str # Default network interface

25

ifaces: dict # Available network interfaces

26

27

# Protocol settings

28

ipv6_enabled: bool # Enable IPv6 support

29

load_layers: list # Protocol layers to load

30

31

# Display settings

32

verb: int # Verbosity level (0-3)

33

color_theme: str # Color theme for output

34

35

# Timeouts and limits

36

timeout: float # Default timeout for operations

37

retry: int # Default retry count

38

39

# File and path settings

40

temp_dir: str # Temporary directory path

41

42

# Platform settings

43

use_pcap: bool # Use libpcap for packet capture

44

use_netifaces: bool # Use netifaces library

45

46

# Global configuration instance

47

conf: Conf

48

```

49

50

### Data Conversion Utilities

51

52

Functions for converting between different data representations and formats.

53

54

```python { .api }

55

def hexdump(x: bytes, dump: bool = False) -> str:

56

"""

57

Create hexadecimal dump of binary data.

58

59

Parameters:

60

- x: Binary data to dump

61

- dump: Return string instead of printing

62

63

Returns:

64

str: Hex dump string (if dump=True)

65

"""

66

67

def linehexdump(x: bytes, onlyasc: bool = 0, onlyhex: bool = 0) -> str:

68

"""

69

Create single-line hex dump.

70

71

Parameters:

72

- x: Binary data to dump

73

- onlyasc: Show only ASCII characters

74

- onlyhex: Show only hex values

75

76

Returns:

77

str: Single-line hex dump

78

"""

79

80

def chexdump(x: bytes) -> str:

81

"""

82

Create colored hex dump.

83

84

Parameters:

85

- x: Binary data to dump

86

87

Returns:

88

str: Colored hex dump

89

"""

90

91

def hexstr(x: bytes, onlyasc: bool = 0, onlyhex: bool = 0) -> str:

92

"""

93

Convert binary data to hex string representation.

94

95

Parameters:

96

- x: Binary data to convert

97

- onlyasc: Include only ASCII printable chars

98

- onlyhex: Include only hex values

99

100

Returns:

101

str: Hex string representation

102

"""

103

104

def mac2str(mac: str) -> bytes:

105

"""

106

Convert MAC address string to binary representation.

107

108

Parameters:

109

- mac: MAC address string (e.g., "aa:bb:cc:dd:ee:ff")

110

111

Returns:

112

bytes: Binary MAC address

113

"""

114

115

def str2mac(s: bytes) -> str:

116

"""

117

Convert binary MAC address to string representation.

118

119

Parameters:

120

- s: Binary MAC address (6 bytes)

121

122

Returns:

123

str: MAC address string

124

"""

125

126

def ltoa(addr: int) -> str:

127

"""

128

Convert long integer to IP address string.

129

130

Parameters:

131

- addr: IP address as 32-bit integer

132

133

Returns:

134

str: IP address string

135

"""

136

137

def atol(addr: str) -> int:

138

"""

139

Convert IP address string to long integer.

140

141

Parameters:

142

- addr: IP address string

143

144

Returns:

145

int: IP address as 32-bit integer

146

"""

147

148

def itom(x: int) -> str:

149

"""

150

Convert integer to netmask string.

151

152

Parameters:

153

- x: Netmask length (0-32)

154

155

Returns:

156

str: Netmask string (e.g., "255.255.255.0")

157

"""

158

```

159

160

### Validation Functions

161

162

Functions for validating network addresses and data formats.

163

164

```python { .api }

165

def valid_mac(mac: str) -> bool:

166

"""

167

Validate MAC address format.

168

169

Parameters:

170

- mac: MAC address string to validate

171

172

Returns:

173

bool: True if valid MAC address format

174

"""

175

176

def valid_ip(ip: str) -> bool:

177

"""

178

Validate IPv4 address format.

179

180

Parameters:

181

- ip: IP address string to validate

182

183

Returns:

184

bool: True if valid IPv4 address

185

"""

186

187

def valid_ip6(ip: str) -> bool:

188

"""

189

Validate IPv6 address format.

190

191

Parameters:

192

- ip: IPv6 address string to validate

193

194

Returns:

195

bool: True if valid IPv6 address

196

"""

197

198

def valid_net(net: str) -> bool:

199

"""

200

Validate network address format (CIDR notation).

201

202

Parameters:

203

- net: Network string to validate (e.g., "192.168.1.0/24")

204

205

Returns:

206

bool: True if valid network format

207

"""

208

```

209

210

### Checksum Functions

211

212

Functions for calculating various network checksums.

213

214

```python { .api }

215

def checksum(data: bytes) -> int:

216

"""

217

Calculate Internet checksum (RFC 1071).

218

219

Parameters:

220

- data: Data to checksum

221

222

Returns:

223

int: 16-bit checksum value

224

"""

225

226

def fletcher16_checksum(data: bytes) -> int:

227

"""

228

Calculate Fletcher-16 checksum.

229

230

Parameters:

231

- data: Data to checksum

232

233

Returns:

234

int: 16-bit Fletcher checksum

235

"""

236

```

237

238

### Network Interface Functions

239

240

Functions for working with network interfaces and routing information.

241

242

```python { .api }

243

def get_if_list() -> list[str]:

244

"""

245

Get list of available network interfaces.

246

247

Returns:

248

list[str]: List of interface names

249

"""

250

251

def get_if_addr(iff: str) -> str:

252

"""

253

Get IP address of network interface.

254

255

Parameters:

256

- iff: Interface name

257

258

Returns:

259

str: IP address of interface

260

"""

261

262

def get_if_hwaddr(iff: str) -> str:

263

"""

264

Get hardware (MAC) address of network interface.

265

266

Parameters:

267

- iff: Interface name

268

269

Returns:

270

str: MAC address of interface

271

"""

272

273

def get_if_raw_hwaddr(iff: str) -> tuple[int, bytes]:

274

"""

275

Get raw hardware address information.

276

277

Parameters:

278

- iff: Interface name

279

280

Returns:

281

tuple: (address_family, raw_address)

282

"""

283

```

284

285

### File and System Utilities

286

287

Utility functions for file operations, temporary files, and system interaction.

288

289

```python { .api }

290

def get_temp_file(keep: bool = False, autoext: str = "", fd: bool = False) -> str:

291

"""

292

Create temporary file.

293

294

Parameters:

295

- keep: Don't delete file automatically

296

- autoext: Automatic file extension

297

- fd: Return file descriptor instead of name

298

299

Returns:

300

str or int: Temporary file path or file descriptor

301

"""

302

303

def get_temp_dir() -> str:

304

"""

305

Get temporary directory path.

306

307

Returns:

308

str: Temporary directory path

309

"""

310

311

def sane(x: bytes, color: bool = False) -> str:

312

"""

313

Sanitize binary data for safe display.

314

315

Parameters:

316

- x: Binary data to sanitize

317

- color: Use color coding for non-printable chars

318

319

Returns:

320

str: Sanitized string representation

321

"""

322

323

def export_object(obj) -> bytes:

324

"""

325

Export Python object to binary format.

326

327

Parameters:

328

- obj: Object to export

329

330

Returns:

331

bytes: Serialized object data

332

"""

333

334

def import_object(data: bytes):

335

"""

336

Import Python object from binary format.

337

338

Parameters:

339

- data: Serialized object data

340

341

Returns:

342

object: Deserialized Python object

343

"""

344

```

345

346

### Random Value Generation

347

348

Functions for generating random values for testing and packet crafting.

349

350

```python { .api }

351

def randstring(length: int) -> str:

352

"""

353

Generate random string of specified length.

354

355

Parameters:

356

- length: String length

357

358

Returns:

359

str: Random string

360

"""

361

362

def randbytes(length: int) -> bytes:

363

"""

364

Generate random bytes of specified length.

365

366

Parameters:

367

- length: Number of bytes

368

369

Returns:

370

bytes: Random bytes

371

"""

372

373

class RandMAC:

374

"""Random MAC address generator."""

375

def __call__(self) -> str:

376

"""Generate random MAC address."""

377

378

class RandIP:

379

"""Random IP address generator."""

380

def __init__(self, net: str = "0.0.0.0/0"):

381

"""

382

Parameters:

383

- net: Network range for random IPs

384

"""

385

386

def __call__(self) -> str:

387

"""Generate random IP address."""

388

389

class RandShort:

390

"""Random 16-bit integer generator."""

391

def __init__(self, min: int = 0, max: int = 65535):

392

"""

393

Parameters:

394

- min: Minimum value

395

- max: Maximum value

396

"""

397

398

def __call__(self) -> int:

399

"""Generate random short integer."""

400

```

401

402

### Session Management

403

404

Functions for managing Scapy sessions and state.

405

406

```python { .api }

407

def save_session(fname: str, session: dict = None, pickleProto: int = -1) -> None:

408

"""

409

Save current Scapy session to file.

410

411

Parameters:

412

- fname: Output filename

413

- session: Session dictionary to save (None for current)

414

- pickleProto: Pickle protocol version

415

"""

416

417

def load_session(fname: str) -> None:

418

"""

419

Load Scapy session from file.

420

421

Parameters:

422

- fname: Session file to load

423

"""

424

425

def update_session(fname: str) -> None:

426

"""

427

Update current session with data from file.

428

429

Parameters:

430

- fname: Session file to load updates from

431

"""

432

433

def restart() -> None:

434

"""

435

Restart Scapy session, clearing all state.

436

"""

437

```

438

439

### Error Handling

440

441

Exception classes and error handling utilities.

442

443

```python { .api }

444

class Scapy_Exception(Exception):

445

"""Base exception class for all Scapy errors."""

446

447

class ScapyInvalidPlatformException(Scapy_Exception):

448

"""Exception for unsupported platform operations."""

449

450

class ScapyNoDstMacException(Scapy_Exception):

451

"""Exception when destination MAC cannot be determined."""

452

453

def warning(msg: str) -> None:

454

"""

455

Display warning message.

456

457

Parameters:

458

- msg: Warning message to display

459

"""

460

```

461

462

### Logging System

463

464

Logging configuration and utilities.

465

466

```python { .api }

467

import logging

468

469

# Scapy loggers

470

log_scapy: logging.Logger # Main Scapy logger

471

log_runtime: logging.Logger # Runtime events logger

472

log_interactive: logging.Logger # Interactive session logger

473

log_loading: logging.Logger # Module loading logger

474

```

475

476

## Usage Examples

477

478

### Configuration Management

479

480

```python

481

from scapy.all import *

482

483

# Check current configuration

484

print(f"Default interface: {conf.iface}")

485

print(f"IPv6 enabled: {conf.ipv6_enabled}")

486

print(f"Verbosity level: {conf.verb}")

487

488

# Modify configuration

489

conf.verb = 2 # Increase verbosity

490

conf.timeout = 5 # Set default timeout to 5 seconds

491

492

# Configure multiple settings

493

conf.configure(

494

verb=1,

495

timeout=3,

496

retry=5,

497

color_theme="colorful"

498

)

499

500

# List available interfaces

501

interfaces = get_if_list()

502

print(f"Available interfaces: {interfaces}")

503

504

# Get interface information

505

if interfaces:

506

iface = interfaces[0]

507

ip_addr = get_if_addr(iface)

508

mac_addr = get_if_hwaddr(iface)

509

print(f"Interface {iface}: IP={ip_addr}, MAC={mac_addr}")

510

```

511

512

### Data Conversion and Validation

513

514

```python

515

# MAC address operations

516

mac_str = "aa:bb:cc:dd:ee:ff"

517

mac_bytes = mac2str(mac_str)

518

mac_back = str2mac(mac_bytes)

519

print(f"MAC: {mac_str} -> {mac_bytes.hex()} -> {mac_back}")

520

521

# IP address operations

522

ip_str = "192.168.1.1"

523

ip_int = atol(ip_str)

524

ip_back = ltoa(ip_int)

525

print(f"IP: {ip_str} -> {ip_int} -> {ip_back}")

526

527

# Validation

528

addresses = ["192.168.1.1", "256.1.1.1", "aa:bb:cc:dd:ee:ff", "invalid:mac"]

529

for addr in addresses:

530

if ":" in addr:

531

valid = valid_mac(addr)

532

addr_type = "MAC"

533

else:

534

valid = valid_ip(addr)

535

addr_type = "IP"

536

print(f"{addr_type} {addr}: {'valid' if valid else 'invalid'}")

537

538

# Network validation

539

networks = ["192.168.1.0/24", "10.0.0.0/8", "invalid/network"]

540

for net in networks:

541

valid = valid_net(net)

542

print(f"Network {net}: {'valid' if valid else 'invalid'}")

543

```

544

545

### Data Display and Analysis

546

547

```python

548

# Create sample packet

549

pkt = IP(dst="8.8.8.8") / TCP(dport=80) / Raw(b"GET / HTTP/1.1\\r\\n\\r\\n")

550

551

# Display packet in different formats

552

print("Standard hex dump:")

553

hexdump(bytes(pkt))

554

555

print("\\nColored hex dump:")

556

print(chexdump(bytes(pkt)))

557

558

print("\\nSingle line hex:")

559

print(linehexdump(bytes(pkt)))

560

561

# Sanitize data for display

562

raw_data = b"Hello\\x00\\x01\\x02World\\xff"

563

sanitized = sane(raw_data, color=True)

564

print(f"Sanitized: {sanitized}")

565

```

566

567

### Random Value Generation

568

569

```python

570

# Generate random values for testing

571

rand_mac = RandMAC()

572

rand_ip = RandIP("192.168.1.0/24")

573

rand_port = RandShort(1024, 65535)

574

575

print("Random values:")

576

for i in range(5):

577

mac = rand_mac()

578

ip = rand_ip()

579

port = rand_port()

580

print(f" MAC: {mac}, IP: {ip}, Port: {port}")

581

582

# Generate random strings and bytes

583

random_str = randstring(10)

584

random_data = randbytes(16)

585

print(f"Random string: {random_str}")

586

print(f"Random bytes: {random_data.hex()}")

587

```

588

589

### File and Session Management

590

591

```python

592

# Save current session

593

variables_to_save = {

594

'my_packets': packets,

595

'target_ips': ["192.168.1.1", "192.168.1.2"],

596

'config_backup': {'verb': conf.verb, 'timeout': conf.timeout}

597

}

598

save_session("my_session.scapy", variables_to_save)

599

600

# Load session later

601

load_session("my_session.scapy")

602

603

# Working with temporary files

604

temp_file = get_temp_file(autoext=".pcap")

605

print(f"Using temporary file: {temp_file}")

606

607

# Write some packets to temp file

608

test_packets = [IP(dst=f"192.168.1.{i}")/ICMP() for i in range(1, 11)]

609

wrpcap(temp_file, test_packets)

610

611

# Read back and verify

612

loaded_packets = rdpcap(temp_file)

613

print(f"Wrote {len(test_packets)} packets, loaded {len(loaded_packets)} packets")

614

```

615

616

### Checksum Calculations

617

618

```python

619

# Calculate checksums for data

620

test_data = b"Hello, World!"

621

inet_checksum = checksum(test_data)

622

fletcher_checksum = fletcher16_checksum(test_data)

623

624

print(f"Data: {test_data}")

625

print(f"Internet checksum: 0x{inet_checksum:04x}")

626

print(f"Fletcher-16 checksum: 0x{fletcher_checksum:04x}")

627

628

# Verify packet checksums

629

ip_pkt = IP(dst="8.8.8.8") / UDP(dport=53) / Raw(b"test")

630

print(f"IP checksum: 0x{ip_pkt.chksum:04x}")

631

print(f"UDP checksum: 0x{ip_pkt[UDP].chksum:04x}")

632

```

633

634

### Error Handling and Logging

635

636

```python

637

import logging

638

639

# Configure logging

640

logging.basicConfig(level=logging.INFO)

641

642

# Use Scapy loggers

643

log_scapy.info("Starting packet analysis")

644

log_runtime.debug("Processing packet batch")

645

646

# Error handling example

647

try:

648

# Attempt operation that might fail

649

invalid_pkt = IP(dst="invalid.address") / ICMP()

650

send(invalid_pkt)

651

except ScapyNoDstMacException as e:

652

warning(f"Could not determine destination MAC: {e}")

653

except Scapy_Exception as e:

654

print(f"Scapy error: {e}")

655

except Exception as e:

656

print(f"General error: {e}")

657

```