77# This file may not be copied, modified, or distributed except according to
88# those terms.
99
10- import net, strutils
10+ import net, chronicles, strutils
1111
1212import ../ switch, ../ multiaddress, ../ multicodec
1313
@@ -17,35 +17,45 @@ proc isIPv4*(ip: IpAddress): bool =
1717proc isIPv6 * (ip: IpAddress ): bool =
1818 ip.family == IpAddressFamily .IPv6
1919
20- proc isPrivate * (ip: string ): bool {.raises : [ValueError ].} =
21- ip.startsWith (" 10." ) or
22- (ip.startsWith (" 172." ) and parseInt (ip.split (" ." )[1 ]) in 16 .. 31 ) or
23- ip.startsWith (" 192.168." ) or ip.startsWith (" 127." ) or ip.startsWith (" 169.254." )
20+ proc isPrivate * (ip: string ): bool {.raises : [].} =
21+ try :
22+ return
23+ ip.startsWith (" 10." ) or
24+ (ip.startsWith (" 172." ) and parseInt (ip.split (" ." )[1 ]) in 16 .. 31 ) or
25+ ip.startsWith (" 192.168." ) or ip.startsWith (" 127." ) or ip.startsWith (" 169.254." )
26+ except ValueError :
27+ return false
2428
25- proc isPrivate * (ip: IpAddress ): bool {.raises : [ValueError ].} =
29+ proc isPrivate * (ip: IpAddress ): bool {.raises : [].} =
2630 isPrivate ($ ip)
2731
28- proc isPublic * (ip: string ): bool {.raises : [ValueError ].} =
32+ proc isPublic * (ip: string ): bool {.raises : [].} =
2933 not isPrivate (ip)
3034
31- proc isPublic * (ip: IpAddress ): bool {.raises : [ValueError ].} =
35+ proc isPublic * (ip: IpAddress ): bool {.raises : [].} =
3236 isPublic ($ ip)
3337
34- proc getPublicIPAddress * (): IpAddress {.raises : [OSError , ValueError ].} =
38+ proc hasPublicIPAddress * (): bool {.raises : [].} =
3539 let ip =
3640 try :
3741 getPrimaryIPAddr ()
38- except OSError as exc:
39- raise exc
40- except ValueError as exc:
41- raise exc
42- except Exception as exc:
43- raise newException (OSError , " Could not get primary IP address" )
44- if not ip.isIPv4 ():
45- raise newException (ValueError , " Host does not have an IPv4 address" )
46- if not ip.isPublic ():
42+ except CatchableError as e:
43+ error " Unable to get primary ip address" , description = e.msg
44+ return false
45+ except Exception as e:
46+ error " Unable to get primary ip address" , description = e.msg
47+ return false
48+ debug " Primary IP address" , ip = ip, isIPv4 = ip.isIPv4 (), isPublic = ip.isPublic ()
49+
50+ return ip.isIPv4 () and ip.isPublic ()
51+
52+ proc getPublicIPAddress * (): IpAddress {.raises : [OSError , ValueError ].} =
53+ if not hasPublicIPAddress ():
4754 raise newException (ValueError , " Host does not have a public IPv4 address" )
48- ip
55+ try :
56+ return getPrimaryIPAddr ()
57+ except Exception as e:
58+ raise newException (OSError , e.msg)
4959
5060proc ipAddrMatches * (
5161 lookup: MultiAddress , addrs: seq [MultiAddress ], ip4: bool = true
0 commit comments