or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-ping3

A pure python3 version of ICMP ping implementation using raw socket.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/ping3@5.1.x

To install, run

npx @tessl/cli install tessl/pypi-ping3@5.1.0

0

# ping3

1

2

A pure Python 3 implementation of ICMP ping functionality using raw sockets. ping3 enables network connectivity testing and monitoring through both programmatic and command-line interfaces, supporting IPv4 and IPv6 protocols with comprehensive error handling and configurable options.

3

4

## Package Information

5

6

- **Package Name**: ping3

7

- **Language**: Python

8

- **Installation**: `pip install ping3`

9

- **Minimum Python Version**: 3.5+

10

11

## Core Imports

12

13

Basic ping functionality:

14

15

```python

16

from ping3 import ping, verbose_ping

17

```

18

19

Module configuration:

20

21

```python

22

import ping3

23

ping3.DEBUG = True # Enable debug output (default False)

24

ping3.EXCEPTIONS = True # Raise exceptions instead of returning None/False (default False)

25

```

26

27

Exception handling:

28

29

```python

30

from ping3.errors import (

31

PingError, Timeout, HostUnknown,

32

DestinationUnreachable, DestinationHostUnreachable,

33

TimeToLiveExpired, TimeExceeded,

34

AddressUnreachable, PortUnreachable

35

)

36

```

37

38

ICMP constants (advanced usage):

39

40

```python

41

from ping3.enums import (

42

ICMP_DEFAULT_CODE,

43

IcmpV4Type, IcmpV6Type,

44

IcmpV4DestinationUnreachableCode, IcmpV6DestinationUnreachableCode,

45

IcmpTimeExceededCode

46

)

47

```

48

49

## Basic Usage

50

51

```python

52

from ping3 import ping, verbose_ping

53

54

# Simple ping - returns delay in seconds

55

delay = ping('example.com')

56

if delay is None:

57

print("Timeout")

58

elif delay is False:

59

print("Error (host unreachable or unknown)")

60

else:

61

print(f"Ping successful: {delay:.3f}s")

62

63

# Ping with custom timeout and get result in milliseconds

64

delay = ping('8.8.8.8', timeout=2, unit='ms')

65

if delay:

66

print(f"Google DNS: {delay:.1f}ms")

67

68

# IPv6 ping

69

delay = ping('2001:4860:4860::8888', version=6)

70

71

# Ping with custom options

72

delay = ping('example.com',

73

timeout=10, # 10 second timeout

74

ttl=64, # Time-to-live

75

size=128, # Payload size in bytes

76

src_addr='192.168.1.100', # Source IP (multi-interface)

77

interface='eth0', # Linux only - network interface

78

seq=5) # ICMP sequence number

79

80

# Verbose ping (like command line ping)

81

verbose_ping('example.com', count=4, interval=1)

82

# Output:

83

# ping 'example.com' ... 215ms

84

# ping 'example.com' ... 216ms

85

# ping 'example.com' ... 219ms

86

# ping 'example.com' ... 217ms

87

```

88

89

## Architecture

90

91

ping3 implements ICMP ping functionality through a clean, socket-based architecture:

92

93

### Socket Management

94

- **Raw Sockets**: Attempts to use `SOCK_RAW` for full control over ICMP packet creation and parsing

95

- **DGRAM Fallback**: Automatically falls back to `SOCK_DGRAM` on permission errors (Linux), where the kernel handles some ICMP details

96

- **Cross-Platform**: Handles platform-specific socket behaviors and IP header presence/absence

97

98

### Packet Flow

99

1. **Address Resolution**: Converts domain names to IP addresses, auto-detects IPv4/IPv6

100

2. **Socket Creation**: Creates appropriate socket type (raw/dgram) for the IP version

101

3. **ICMP Packet Construction**: Builds ICMP header with ID, sequence, checksum, and timestamp payload

102

4. **Transmission**: Sends packet via socket with configurable TTL, source binding, and interface selection

103

5. **Response Handling**: Receives and parses ICMP responses, calculates round-trip time

104

105

### Error Handling Strategy

106

- **Dual Mode**: Returns `None`/`False` by default, or raises exceptions when `EXCEPTIONS=True`

107

- **Comprehensive Errors**: Specific exception types for different failure modes (timeout, unreachable, TTL expired)

108

- **Debug Support**: Optional debug output showing packet headers and transmission details

109

110

This design provides both simplicity for basic use cases and full control for advanced network diagnostics.

111

112

## Capabilities

113

114

### Core Ping Functions

115

116

Primary ping functionality for sending ICMP packets and measuring network latency.

117

118

```python { .api }

119

def ping(dest_addr: str, timeout: int = 4, unit: str = "s", src_addr: str = "",

120

ttl=None, seq: int = 0, size: int = 56, interface: str = "",

121

version=None) -> float | None | bool:

122

"""

123

Send one ping to destination address with configurable options.

124

125

Parameters:

126

- dest_addr (str): Destination IP address or domain name (e.g., "192.168.1.1", "example.com", "2001:db8::1")

127

- timeout (int): Response timeout in seconds (default 4)

128

- unit (str): Return unit "s" for seconds or "ms" for milliseconds (default "s")

129

- src_addr (str): Source IP address for multi-interface systems (default "")

130

- ttl (int|None): Time-To-Live value, None uses OS default (default None)

131

- seq (int): ICMP packet sequence number (default 0)

132

- size (int): ICMP payload size in bytes (default 56)

133

- interface (str): Linux only - network interface name like "eth0" (default "")

134

- version (int|None): IP version 4 or 6, None for auto-detect (default None)

135

136

Returns:

137

float|None|False: Delay in seconds/milliseconds, None on timeout, False on error

138

139

Raises:

140

PingError: Any ping-related error if ping3.EXCEPTIONS is True

141

"""

142

143

def verbose_ping(dest_addr: str, count: int = 4, interval: float = 0,

144

*args, **kwargs) -> None:

145

"""

146

Send multiple pings with formatted output display.

147

148

Parameters:

149

- dest_addr (str): Destination IP address or domain name

150

- count (int): Number of pings to send, 0 for infinite loop (default 4)

151

- interval (float): Seconds between pings, 0 for immediate (default 0)

152

- *args, **kwargs: All ping() arguments except seq

153

154

Returns:

155

None: Prints formatted results to stdout

156

"""

157

```

158

159

160

## Configuration

161

162

### Global Settings

163

164

```python { .api }

165

# Module-level configuration constants

166

DEBUG: bool # Enable debug output (default False)

167

EXCEPTIONS: bool # Raise exceptions instead of returning None/False (default False)

168

LOGGER: object # Logger instance for debug output (default None)

169

__version__: str # Package version string (currently "5.1.5")

170

```

171

172

### Command Line Interface

173

174

The package provides a `ping3` command-line tool with full argument support:

175

176

```bash

177

# Basic usage

178

ping3 example.com

179

180

# With options

181

ping3 -c 10 -t 2 -i 0.5 -s 64 example.com

182

183

# IPv6 ping

184

ping3 -6 2001:4860:4860::8888

185

186

# Help

187

ping3 --help

188

```

189

190

## Exception Handling

191

192

### Exception Hierarchy

193

194

```python { .api }

195

class PingError(Exception):

196

"""Base exception for all ping-related errors."""

197

198

class TimeExceeded(PingError):

199

"""Base exception for time-related errors."""

200

201

class TimeToLiveExpired(TimeExceeded):

202

"""Exception when TTL expires during routing."""

203

# Attributes: ip_header, icmp_header, message

204

205

class DestinationUnreachable(PingError):

206

"""Base exception for unreachable destinations."""

207

# Attributes: ip_header, icmp_header, message

208

209

class DestinationHostUnreachable(DestinationUnreachable):

210

"""Exception for unreachable hosts (IPv4)."""

211

# Attributes: ip_header, icmp_header, message

212

213

class AddressUnreachable(DestinationUnreachable):

214

"""Exception for unreachable IPv6 addresses."""

215

# Attributes: ip_header, icmp_header, message

216

217

class PortUnreachable(DestinationUnreachable):

218

"""Exception for unreachable ports."""

219

# Attributes: ip_header, icmp_header, message

220

221

class HostUnknown(PingError):

222

"""Exception for unresolvable hostnames."""

223

# Attributes: dest_addr, message

224

225

class Timeout(PingError):

226

"""Exception for ping timeouts."""

227

# Attributes: timeout, message

228

```

229

230

### Error Handling Patterns

231

232

```python

233

from ping3 import ping

234

from ping3.errors import PingError, Timeout, HostUnknown

235

236

# Method 1: Check return values (default behavior)

237

result = ping('example.com')

238

if result is None:

239

print("Ping timed out")

240

elif result is False:

241

print("Ping failed (host unreachable or unknown)")

242

else:

243

print(f"Ping successful: {result:.3f}s")

244

245

# Method 2: Exception handling

246

import ping3

247

ping3.EXCEPTIONS = True # Enable exception mode

248

249

try:

250

delay = ping('example.com')

251

print(f"Ping successful: {delay:.3f}s")

252

except Timeout:

253

print("Ping timed out")

254

except HostUnknown:

255

print("Host could not be resolved")

256

except PingError as e:

257

print(f"Ping failed: {e}")

258

```

259

260

## ICMP Constants and Enums

261

262

### ICMP Type Constants

263

264

```python { .api }

265

ICMP_DEFAULT_CODE = 0 # Default code for ECHO_REPLY and ECHO_REQUEST

266

267

class IcmpV4Type(enum.IntEnum):

268

"""ICMPv4 message type constants."""

269

ECHO_REPLY = 0

270

DESTINATION_UNREACHABLE = 3

271

REDIRECT_MESSAGE = 5

272

ECHO_REQUEST = 8

273

ROUTER_ADVERTISEMENT = 9

274

ROUTER_SOLICITATION = 10

275

TIME_EXCEEDED = 11

276

BAD_IP_HEADER = 12

277

TIMESTAMP = 13

278

TIMESTAMP_REPLY = 14

279

280

class IcmpV6Type(enum.IntEnum):

281

"""ICMPv6 message type constants."""

282

DESTINATION_UNREACHABLE = 1

283

TIME_EXCEEDED = 3

284

ECHO_REQUEST = 128

285

ECHO_REPLY = 129

286

ROUTER_SOLICITATION = 133

287

ROUTER_ADVERTISEMENT = 134

288

REDIRECT_MESSAGE = 137

289

```

290

291

### ICMP Code Constants

292

293

```python { .api }

294

class IcmpV4DestinationUnreachableCode(enum.IntEnum):

295

"""ICMPv4 destination unreachable code constants."""

296

DESTINATION_NETWORK_UNREACHABLE = 0

297

DESTINATION_HOST_UNREACHABLE = 1

298

DESTINATION_PROTOCOL_UNREACHABLE = 2

299

DESTINATION_PORT_UNREACHABLE = 3

300

FRAGMENTATION_REQUIRED = 4

301

SOURCE_ROUTE_FAILED = 5

302

DESTINATION_NETWORK_UNKNOWN = 6

303

DESTINATION_HOST_UNKNOWN = 7

304

SOURCE_HOST_ISOLATED = 8

305

NETWORK_ADMINISTRATIVELY_PROHIBITED = 9

306

HOST_ADMINISTRATIVELY_PROHIBITED = 10

307

NETWORK_UNREACHABLE_FOR_TOS = 11

308

HOST_UNREACHABLE_FOR_TOS = 12

309

COMMUNICATION_ADMINISTRATIVELY_PROHIBITED = 13

310

HOST_PRECEDENCE_VIOLATION = 14

311

PRECEDENCE_CUTOFF_IN_EFFECT = 15

312

313

class IcmpV6DestinationUnreachableCode(enum.IntEnum):

314

"""ICMPv6 destination unreachable code constants."""

315

NO_ROUTE_TO_DESTINATION = 0

316

COMMUNICATION_PROHIBITED = 1

317

BEYOND_SCOPE = 2

318

ADDRESS_UNREACHABLE = 3

319

PORT_UNREACHABLE = 4

320

SOURCE_ADDRESS_FAILED = 5

321

REJECT_ROUTE_TO_DESTINATION = 6

322

ERROR_IN_SOURCE_ROUTING_HEADER = 7

323

324

class IcmpTimeExceededCode(enum.IntEnum):

325

"""ICMP time exceeded code constants for both IPv4 and IPv6."""

326

TTL_EXPIRED = 0

327

FRAGMENT_REASSEMBLY_TIME_EXCEEDED = 1

328

```

329

330

## Platform Considerations

331

332

### Permissions

333

334

- **Root/Administrator Required**: ICMP ping requires raw socket access on most platforms

335

- **Linux Unprivileged**: Falls back to DGRAM sockets with kernel ICMP ID rewriting

336

- **Windows**: Requires administrator privileges for raw sockets

337

- **macOS**: Requires root privileges for raw sockets

338

339

### Cross-Platform Compatibility

340

341

- **IPv4 Support**: Full support on all platforms (Windows, Linux, macOS)

342

- **IPv6 Support**: Full support with automatic address family detection

343

- **Interface Binding**: Linux-only feature using SO_BINDTODEVICE

344

- **Source Address**: IPv4 source binding supported, IPv6 uses OS routing

345

346

### Socket Types

347

348

ping3 automatically handles socket type selection:

349

- Attempts `SOCK_RAW` first for full control

350

- Falls back to `SOCK_DGRAM` on permission errors (Linux)

351

- Handles platform-specific IP header presence/absence