Total Complexity | 7 |
Total Lines | 52 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | """ |
||
2 | syslog2irc.network |
||
3 | ~~~~~~~~~~~~~~~~~~ |
||
4 | |||
5 | :Copyright: 2007-2021 Jochen Kupperschmidt |
||
6 | :License: MIT, see LICENSE for details. |
||
7 | """ |
||
8 | |||
9 | from dataclasses import dataclass |
||
10 | from enum import Enum |
||
11 | |||
12 | |||
13 | TransportProtocol = Enum('TransportProtocol', ['TCP', 'UDP']) |
||
14 | |||
15 | |||
16 | @dataclass(frozen=True) |
||
17 | class Port: |
||
18 | """A network port.""" |
||
19 | |||
20 | number: int |
||
21 | transport_protocol: TransportProtocol |
||
22 | |||
23 | |||
24 | def format_port(port: Port) -> str: |
||
25 | """Return string representation for port.""" |
||
26 | return f'{port.number}/{port.transport_protocol.name.lower()}' |
||
27 | |||
28 | |||
29 | def parse_port(value: str) -> Port: |
||
30 | """Extract port number and protocol from string representation.""" |
||
31 | tokens = value.split('/', maxsplit=1) |
||
32 | if len(tokens) != 2: |
||
33 | raise ValueError(f'Invalid port string "{value}"') |
||
34 | |||
35 | number_str = tokens[0] |
||
36 | try: |
||
37 | number = int(number_str) |
||
38 | except ValueError: |
||
39 | raise ValueError(f'Invalid port number "{number_str}"') |
||
40 | if number < 1 or number > 65535: |
||
41 | raise ValueError(f'Invalid port number "{number_str}"') |
||
42 | |||
43 | transport_protocol_str = tokens[1] |
||
44 | try: |
||
45 | transport_protocol = TransportProtocol[transport_protocol_str.upper()] |
||
46 | except KeyError: |
||
47 | raise ValueError( |
||
48 | f'Unknown transport protocol "{transport_protocol_str}"' |
||
49 | ) |
||
50 | |||
51 | return Port(number=number, transport_protocol=transport_protocol) |
||
52 |