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

core-packet-system.mddocs/

0

# Core Packet System

1

2

The foundation of Scapy's packet manipulation capabilities, providing the Packet base class, field system, and core operations for building, parsing, and manipulating network packets.

3

4

## Capabilities

5

6

### Packet Base Class

7

8

The core Packet class that represents all network packets in Scapy, providing methods for display, manipulation, serialization, and layer access.

9

10

```python { .api }

11

class Packet:

12

"""

13

Base class for all network packets in Scapy.

14

"""

15

def __init__(self, *args, **kwargs):

16

"""

17

Initialize a packet with optional field values.

18

19

Parameters:

20

- *args: Positional arguments for packet construction

21

- **kwargs: Field values as keyword arguments

22

"""

23

24

def show(self, dump: bool = False, indent: int = 3, lvl: str = "", label_lvl: str = "") -> None:

25

"""

26

Display packet contents in a readable format.

27

28

Parameters:

29

- dump: Return string instead of printing (default False)

30

- indent: Indentation level for nested display

31

- lvl: Current level string for formatting

32

- label_lvl: Label level for formatting

33

"""

34

35

def summary(self) -> str:

36

"""

37

Return a one-line summary of the packet.

38

39

Returns:

40

str: Packet summary string

41

"""

42

43

def build(self) -> bytes:

44

"""

45

Build the binary representation of the packet.

46

47

Returns:

48

bytes: Binary packet data

49

"""

50

51

def dissect(self, s: bytes) -> None:

52

"""

53

Parse binary data into packet fields.

54

55

Parameters:

56

- s: Binary data to parse

57

"""

58

59

def copy(self):

60

"""

61

Create a deep copy of the packet.

62

63

Returns:

64

Packet: Copy of the packet

65

"""

66

67

def getlayer(self, cls, nb: int = 1):

68

"""

69

Get a specific layer from the packet.

70

71

Parameters:

72

- cls: Layer class or index to retrieve

73

- nb: Layer number (for multiple layers of same type)

74

75

Returns:

76

Packet or None: The requested layer

77

"""

78

79

def haslayer(self, cls) -> bool:

80

"""

81

Check if packet contains a specific layer.

82

83

Parameters:

84

- cls: Layer class to check for

85

86

Returns:

87

bool: True if layer is present

88

"""

89

90

def sprintf(self, fmt: str) -> str:

91

"""

92

Format packet contents using a format string.

93

94

Parameters:

95

- fmt: Format string with field references

96

97

Returns:

98

str: Formatted string

99

"""

100

101

def __div__(self, other):

102

"""Stack packets using the / operator."""

103

104

def __truediv__(self, other):

105

"""Stack packets using the / operator (Python 3)."""

106

```

107

108

### Raw Data Packet

109

110

Represents raw binary data that doesn't correspond to any specific protocol.

111

112

```python { .api }

113

class Raw(Packet):

114

"""

115

Packet containing raw binary data.

116

"""

117

def __init__(self, load: bytes = b""):

118

"""

119

Initialize with raw binary data.

120

121

Parameters:

122

- load: Binary data payload

123

"""

124

```

125

126

### Padding Packet

127

128

Represents padding data, typically used to fill packets to minimum size requirements.

129

130

```python { .api }

131

class Padding(Raw):

132

"""

133

Padding packet for filling space in network frames.

134

"""

135

```

136

137

### NoPayload Class

138

139

Represents the absence of a payload in a packet.

140

141

```python { .api }

142

class NoPayload:

143

"""

144

Represents no payload/end of packet layers.

145

"""

146

```

147

148

### Layer Binding

149

150

Functions for managing how protocol layers are automatically recognized and bound together.

151

152

```python { .api }

153

def bind_layers(lower, upper, **kwargs) -> None:

154

"""

155

Bind two protocol layers together.

156

157

Parameters:

158

- lower: Lower layer class

159

- upper: Upper layer class

160

- **kwargs: Binding conditions (field values)

161

"""

162

163

def split_layers(lower, upper, **kwargs) -> None:

164

"""

165

Remove binding between two protocol layers.

166

167

Parameters:

168

- lower: Lower layer class

169

- upper: Upper layer class

170

- **kwargs: Binding conditions to remove

171

"""

172

```

173

174

### Packet Exploration

175

176

Interactive packet exploration and analysis functions.

177

178

```python { .api }

179

def explore(p: Packet) -> None:

180

"""

181

Start interactive exploration of a packet.

182

183

Parameters:

184

- p: Packet to explore

185

"""

186

```

187

188

## Field System

189

190

### Core Field Classes

191

192

Base field types for defining packet structure and data types.

193

194

```python { .api }

195

class Field:

196

"""

197

Base class for packet fields.

198

"""

199

def __init__(self, name: str, default, fmt: str = "H"):

200

"""

201

Initialize a field.

202

203

Parameters:

204

- name: Field name

205

- default: Default value

206

- fmt: Struct format string

207

"""

208

209

class RawVal:

210

"""

211

Wrapper for raw values in fields.

212

"""

213

```

214

215

### Network Address Fields

216

217

Fields for handling network addresses like IP addresses and MAC addresses.

218

219

```python { .api }

220

class IPField(Field):

221

"""IPv4 address field."""

222

def __init__(self, name: str, default: str):

223

"""

224

Parameters:

225

- name: Field name

226

- default: Default IP address

227

"""

228

229

class IP6Field(Field):

230

"""IPv6 address field."""

231

232

class MACField(Field):

233

"""MAC address field."""

234

def __init__(self, name: str, default: str):

235

"""

236

Parameters:

237

- name: Field name

238

- default: Default MAC address

239

"""

240

```

241

242

### Numeric Fields

243

244

Fields for various integer sizes and formats.

245

246

```python { .api }

247

class ByteField(Field):

248

"""8-bit unsigned integer field."""

249

250

class ShortField(Field):

251

"""16-bit unsigned integer field."""

252

253

class IntField(Field):

254

"""32-bit unsigned integer field."""

255

256

class LongField(Field):

257

"""64-bit unsigned integer field."""

258

259

class XByteField(Field):

260

"""8-bit integer displayed in hexadecimal."""

261

262

class XShortField(Field):

263

"""16-bit integer displayed in hexadecimal."""

264

265

class XIntField(Field):

266

"""32-bit integer displayed in hexadecimal."""

267

```

268

269

### String Fields

270

271

Fields for handling string and binary data.

272

273

```python { .api }

274

class StrField(Field):

275

"""Variable-length string field."""

276

def __init__(self, name: str, default: str, fmt: str = "H"):

277

"""

278

Parameters:

279

- name: Field name

280

- default: Default string value

281

- fmt: Length format

282

"""

283

284

class StrFixedLenField(Field):

285

"""Fixed-length string field."""

286

def __init__(self, name: str, default: str, length: int):

287

"""

288

Parameters:

289

- name: Field name

290

- default: Default string value

291

- length: Fixed string length

292

"""

293

294

class StrLenField(Field):

295

"""Length-prefixed string field."""

296

297

class StrNullField(Field):

298

"""Null-terminated string field."""

299

```

300

301

### Enumeration Fields

302

303

Fields that map numeric values to symbolic names.

304

305

```python { .api }

306

class EnumField(Field):

307

"""Enumeration field mapping numbers to names."""

308

def __init__(self, name: str, default, enum: dict, fmt: str = "H"):

309

"""

310

Parameters:

311

- name: Field name

312

- default: Default value

313

- enum: Dictionary mapping values to names

314

- fmt: Struct format

315

"""

316

317

class ByteEnumField(EnumField):

318

"""8-bit enumeration field."""

319

320

class ShortEnumField(EnumField):

321

"""16-bit enumeration field."""

322

323

class IntEnumField(EnumField):

324

"""32-bit enumeration field."""

325

```

326

327

### Bit Fields

328

329

Fields for handling individual bits and bit flags.

330

331

```python { .api }

332

class BitField(Field):

333

"""Individual bit field."""

334

def __init__(self, name: str, default: int, size: int):

335

"""

336

Parameters:

337

- name: Field name

338

- default: Default value

339

- size: Number of bits

340

"""

341

342

class FlagsField(BitField):

343

"""Bit flags field with named flags."""

344

def __init__(self, name: str, default: int, size: int, names: list):

345

"""

346

Parameters:

347

- name: Field name

348

- default: Default value

349

- size: Number of bits

350

- names: List of flag names

351

"""

352

```

353

354

### Conditional Fields

355

356

Fields that are conditionally present based on other field values.

357

358

```python { .api }

359

class ConditionalField(Field):

360

"""Field that is conditionally present."""

361

def __init__(self, fld: Field, cond):

362

"""

363

Parameters:

364

- fld: The actual field

365

- cond: Condition function

366

"""

367

368

class PadField(Field):

369

"""Padding field."""

370

371

class ActionField(Field):

372

"""Field that performs actions during packet processing."""

373

```

374

375

## Usage Examples

376

377

### Basic Packet Creation

378

379

```python

380

from scapy.all import *

381

382

# Create a simple packet

383

pkt = IP(dst="192.168.1.1") / TCP(dport=80)

384

385

# Show packet structure

386

pkt.show()

387

388

# Get packet summary

389

print(pkt.summary())

390

391

# Build binary representation

392

binary = pkt.build()

393

print(f"Packet size: {len(binary)} bytes")

394

```

395

396

### Layer Manipulation

397

398

```python

399

# Create layered packet

400

pkt = Ether() / IP(dst="8.8.8.8") / UDP(dport=53) / DNS(qd=DNSQR(qname="example.com"))

401

402

# Access specific layers

403

ip_layer = pkt.getlayer(IP)

404

dns_layer = pkt[DNS]

405

406

# Check for layer presence

407

if pkt.haslayer(TCP):

408

print("Has TCP layer")

409

410

# Modify layer fields

411

pkt[IP].ttl = 64

412

pkt[UDP].dport = 5353

413

```

414

415

### Custom Field Usage

416

417

```python

418

# Working with raw data

419

raw_pkt = Raw(b"\\x48\\x65\\x6c\\x6c\\x6f") # "Hello"

420

raw_pkt.show()

421

422

# Layer binding example

423

bind_layers(TCP, HTTP, dport=80)

424

bind_layers(TCP, HTTP, sport=80)

425

426

# Now TCP packets to/from port 80 will auto-decode as HTTP

427

```