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

send-receive.mddocs/

0

# Send/Receive Operations

1

2

Network I/O functions for sending packets, receiving responses, capturing traffic, and managing network communication across different platforms and socket types.

3

4

## Capabilities

5

6

### Send and Receive with Answers

7

8

Core functions for sending packets and collecting responses, enabling interactive network communication and analysis.

9

10

```python { .api }

11

def sr(x, promisc: bool = None, filter: str = None, timeout: float = None,

12

inter: float = 0, verbose: int = None, chainCC: bool = False,

13

retry: int = 0, multi: bool = False, **kwargs) -> tuple[SndRcvList, PacketList]:

14

"""

15

Send packets and receive answers.

16

17

Parameters:

18

- x: Packet(s) to send

19

- promisc: Enable promiscuous mode

20

- filter: BPF filter for received packets

21

- timeout: Timeout in seconds (None for no timeout)

22

- inter: Inter-packet interval in seconds

23

- verbose: Verbosity level (0=quiet, 1=normal, 2=verbose)

24

- chainCC: Chain packet completion callbacks

25

- retry: Number of retries for unanswered packets

26

- multi: Allow multiple answers per packet

27

- **kwargs: Additional arguments for socket

28

29

Returns:

30

tuple: (answered_packets, unanswered_packets)

31

"""

32

33

def sr1(x, promisc: bool = None, filter: str = None, timeout: float = None,

34

verbose: int = None, retry: int = 0, **kwargs) -> Packet:

35

"""

36

Send packets and receive first answer.

37

38

Parameters:

39

- x: Packet(s) to send

40

- timeout: Timeout in seconds

41

- verbose: Verbosity level

42

- retry: Number of retries

43

- filter: BPF filter for received packets

44

- iface: Interface to use

45

- **kwargs: Additional socket arguments

46

47

Returns:

48

Packet or None: First received packet or None if timeout

49

"""

50

51

def srp(x, timeout: float = None, verbose: int = None, retry: int = 3,

52

multi: bool = False, filter: str = None, iface: str = None,

53

**kwargs) -> tuple[SndRcvList, PacketList]:

54

"""

55

Send packets at layer 2 and receive answers.

56

57

Parameters:

58

- x: Packet(s) to send

59

- timeout: Timeout in seconds

60

- verbose: Verbosity level

61

- retry: Number of retries

62

- multi: Allow multiple answers per packet

63

- filter: BPF filter for received packets

64

- iface: Interface to use

65

- **kwargs: Additional socket arguments

66

67

Returns:

68

tuple: (answered_packets, unanswered_packets)

69

"""

70

71

def srp1(x, timeout: float = None, verbose: int = None, retry: int = 3,

72

filter: str = None, iface: str = None, **kwargs) -> Packet:

73

"""

74

Send packets at layer 2 and receive first answer.

75

76

Parameters:

77

- x: Packet(s) to send

78

- timeout: Timeout in seconds

79

- verbose: Verbosity level

80

- retry: Number of retries

81

- filter: BPF filter for received packets

82

- iface: Interface to use

83

- **kwargs: Additional socket arguments

84

85

Returns:

86

Packet or None: First received packet or None if timeout

87

"""

88

```

89

90

### Send-Only Operations

91

92

Functions for sending packets without waiting for responses, useful for traffic generation and one-way communication.

93

94

```python { .api }

95

def send(x, inter: float = 0, loop: int = 0, count: int = None,

96

verbose: int = None, realtime: bool = None, return_packets: bool = False,

97

socket: 'SuperSocket' = None, **kwargs) -> None:

98

"""

99

Send packets at layer 3.

100

101

Parameters:

102

- x: Packet(s) to send

103

- inter: Inter-packet interval in seconds

104

- loop: Loop forever if 1, or number of loops

105

- count: Number of packets to send

106

- verbose: Verbosity level

107

- realtime: Send at real-time intervals

108

- return_packets: Return sent packets

109

- socket: Socket to use for sending

110

- **kwargs: Additional arguments

111

"""

112

113

def sendp(x, inter: float = 0, loop: int = 0, count: int = None,

114

verbose: int = None, realtime: bool = None, return_packets: bool = False,

115

iface: str = None, socket: 'SuperSocket' = None, **kwargs) -> None:

116

"""

117

Send packets at layer 2.

118

119

Parameters:

120

- x: Packet(s) to send

121

- inter: Inter-packet interval in seconds

122

- loop: Loop forever if 1, or number of loops

123

- count: Number of packets to send

124

- verbose: Verbosity level

125

- realtime: Send at real-time intervals

126

- return_packets: Return sent packets

127

- iface: Interface to send on

128

- socket: Socket to use for sending

129

- **kwargs: Additional arguments

130

"""

131

132

def sendpfast(x, pps: int = None, mbps: float = None, realtime: bool = None,

133

loop: int = 0, file_cache: bool = False, iface: str = None) -> None:

134

"""

135

Send packets at high speed using tcpreplay.

136

137

Parameters:

138

- x: Packet(s) to send

139

- pps: Packets per second

140

- mbps: Megabits per second

141

- realtime: Send at recorded intervals

142

- loop: Number of loops

143

- file_cache: Use file caching

144

- iface: Interface to send on

145

"""

146

```

147

148

### Packet Capture

149

150

Functions for capturing network traffic with flexible filtering and processing options.

151

152

```python { .api }

153

def sniff(count: int = 0, store: bool = True, offline: str = None,

154

prn: callable = None, lfilter: callable = None,

155

L2socket: 'SuperSocket' = None, timeout: float = None,

156

opened_socket: 'SuperSocket' = None, stop_filter: callable = None,

157

iface: str = None, started_callback: callable = None,

158

filter: str = None, **kwargs) -> PacketList:

159

"""

160

Capture packets from the network.

161

162

Parameters:

163

- count: Number of packets to capture (0=infinite)

164

- store: Store captured packets in memory

165

- offline: Read from pcap file instead of network

166

- prn: Function to apply to each packet as it arrives

167

- lfilter: Python function to filter packets

168

- L2socket: Socket to use for capture

169

- timeout: Stop after timeout seconds

170

- opened_socket: Use existing socket

171

- stop_filter: Function to determine when to stop

172

- iface: Interface to capture on

173

- started_callback: Function called when capture starts

174

- filter: BPF filter string

175

- **kwargs: Additional arguments

176

177

Returns:

178

PacketList: Captured packets (if store=True)

179

"""

180

181

class AsyncSniffer:

182

"""

183

Asynchronous packet sniffer that runs in background.

184

"""

185

def __init__(self, count: int = 0, store: bool = True, prn: callable = None,

186

filter: str = None, iface: str = None, **kwargs):

187

"""

188

Initialize asynchronous sniffer.

189

190

Parameters:

191

- count: Number of packets to capture

192

- store: Store packets in memory

193

- prn: Function to apply to each packet

194

- filter: BPF filter string

195

- iface: Interface to capture on

196

- **kwargs: Additional sniff arguments

197

"""

198

199

def start(self) -> None:

200

"""Start packet capture in background thread."""

201

202

def stop(self) -> None:

203

"""Stop packet capture."""

204

205

def join(self, timeout: float = None) -> None:

206

"""Wait for capture to complete."""

207

208

@property

209

def results(self) -> PacketList:

210

"""Get captured packets."""

211

```

212

213

### Socket Interface

214

215

Low-level send and receive operations using Scapy's socket abstraction.

216

217

```python { .api }

218

def sndrcv(pks: 'SuperSocket', pkt: Packet, timeout: float = 2,

219

verbose: int = None) -> tuple[Packet, float]:

220

"""

221

Low-level send and receive operation.

222

223

Parameters:

224

- pks: Socket for sending/receiving

225

- pkt: Packet to send

226

- timeout: Receive timeout

227

- verbose: Verbosity level

228

229

Returns:

230

tuple: (received_packet, timestamp)

231

"""

232

233

def sndrcvflood(pks: 'SuperSocket', pkt: Packet, ans: Packet = None,

234

stopevent: 'Event' = None, **kwargs) -> None:

235

"""

236

Send packet in flood mode and receive answers.

237

238

Parameters:

239

- pks: Socket for operations

240

- pkt: Packet to send repeatedly

241

- ans: Expected answer packet

242

- stopevent: Event to stop flooding

243

- **kwargs: Additional arguments

244

"""

245

```

246

247

### External Tool Integration

248

249

Integration with external network tools for extended functionality.

250

251

```python { .api }

252

def tshark(*args, **kwargs) -> PacketList:

253

"""

254

Use tshark for packet capture with advanced filtering.

255

256

Parameters:

257

- *args: Arguments passed to tshark

258

- **kwargs: Keyword arguments

259

260

Returns:

261

PacketList: Captured packets

262

"""

263

264

def tcpdump(count: int = None, **kwargs) -> PacketList:

265

"""

266

Use tcpdump for packet capture.

267

268

Parameters:

269

- count: Number of packets to capture

270

- **kwargs: Additional tcpdump arguments

271

272

Returns:

273

PacketList: Captured packets

274

"""

275

```

276

277

### Debug Information

278

279

Debug information container for troubleshooting send/receive operations.

280

281

```python { .api }

282

class debug:

283

"""

284

Debug information for send/receive operations.

285

"""

286

recv: PacketList # Received packets

287

sent: PacketList # Sent packets

288

match: list # Matched packet pairs

289

```

290

291

## Socket Types

292

293

### SuperSocket Base

294

295

```python { .api }

296

class SuperSocket:

297

"""

298

Abstract base class for all Scapy sockets.

299

"""

300

def send(self, x: Packet) -> int:

301

"""Send a packet."""

302

303

def recv(self, x: int = None) -> Packet:

304

"""Receive a packet."""

305

306

def close(self) -> None:

307

"""Close the socket."""

308

```

309

310

### Layer-Specific Sockets

311

312

```python { .api }

313

class L2Socket(SuperSocket):

314

"""Layer 2 socket for Ethernet-level communication."""

315

316

class L3Socket(SuperSocket):

317

"""Layer 3 socket for IP-level communication."""

318

319

class L2ListenSocket(SuperSocket):

320

"""Layer 2 listening socket."""

321

322

class L3ListenSocket(SuperSocket):

323

"""Layer 3 listening socket."""

324

```

325

326

## Usage Examples

327

328

### Basic Send/Receive

329

330

```python

331

from scapy.all import *

332

333

# Send ICMP ping and wait for reply

334

packet = IP(dst="8.8.8.8") / ICMP()

335

reply = sr1(packet, timeout=2)

336

if reply:

337

print(f"Received reply from {reply.src}")

338

reply.show()

339

340

# Send TCP SYN and collect responses

341

syn_packets = [IP(dst="example.com")/TCP(dport=p, flags="S") for p in [22,80,443]]

342

answered, unanswered = sr(syn_packets, timeout=1)

343

answered.summary()

344

```

345

346

### Packet Capture

347

348

```python

349

# Capture 10 HTTP packets

350

packets = sniff(count=10, filter="tcp port 80")

351

packets.summary()

352

353

# Capture with custom processing

354

def packet_processor(pkt):

355

if pkt.haslayer(TCP):

356

print(f"TCP packet: {pkt[IP].src}:{pkt[TCP].sport} -> {pkt[IP].dst}:{pkt[TCP].dport}")

357

358

sniff(prn=packet_processor, filter="tcp", count=20)

359

360

# Asynchronous capture

361

sniffer = AsyncSniffer(filter="icmp", count=5)

362

sniffer.start()

363

# ... do other work ...

364

sniffer.join()

365

print(f"Captured {len(sniffer.results)} packets")

366

```

367

368

### High-Speed Sending

369

370

```python

371

# Send packets continuously

372

packets = [IP(dst="192.168.1.1")/UDP(dport=p)/Raw(b"test") for p in range(1000, 2000)]

373

send(packets, inter=0.001) # 1ms interval

374

375

# Layer 2 sending

376

eth_packets = [Ether(dst="aa:bb:cc:dd:ee:ff")/IP(dst="192.168.1.1")/ICMP() for _ in range(100)]

377

sendp(eth_packets, inter=0.01, iface="eth0")

378

379

# High-speed sending with tcpreplay

380

sendpfast(packets, pps=1000, iface="eth0")

381

```

382

383

### Advanced Filtering

384

385

```python

386

# Capture with complex filter

387

def custom_filter(pkt):

388

return (pkt.haslayer(TCP) and

389

pkt[TCP].dport == 80 and

390

len(pkt) > 100)

391

392

web_traffic = sniff(lfilter=custom_filter, timeout=30)

393

394

# Capture until specific condition

395

def stop_condition(pkt):

396

return pkt.haslayer(DNS) and "evil.com" in str(pkt[DNS].qd.qname)

397

398

packets = sniff(stop_filter=stop_condition, timeout=60)

399

```

400

401

### Protocol-Specific Operations

402

403

```python

404

# ARP scanning

405

arp_requests = [Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=f"192.168.1.{i}")

406

for i in range(1, 255)]

407

answered, unanswered = srp(arp_requests, timeout=2, verbose=0)

408

409

# DNS queries

410

dns_queries = [IP(dst="8.8.8.8")/UDP(dport=53)/DNS(rd=1, qd=DNSQR(qname=host))

411

for host in ["google.com", "facebook.com", "github.com"]]

412

answers = sr1(dns_queries, timeout=3)

413

414

# TCP port scanning

415

def tcp_scan(target, ports):

416

syn_packets = [IP(dst=target)/TCP(dport=port, flags="S") for port in ports]

417

answered, unanswered = sr(syn_packets, timeout=1, verbose=0)

418

419

open_ports = []

420

for sent, received in answered:

421

if received.haslayer(TCP) and received[TCP].flags == 18: # SYN-ACK

422

open_ports.append(sent[TCP].dport)

423

424

return open_ports

425

426

open_ports = tcp_scan("example.com", [22, 80, 443, 8080])

427

print(f"Open ports: {open_ports}")

428

```