ip-netmask
This commit is contained in:
parent
7505e181ea
commit
a577fadf94
24
iputil.rkt
24
iputil.rkt
|
@ -1,14 +1,18 @@
|
|||
#lang racket
|
||||
|
||||
(require racket/struct)
|
||||
|
||||
(provide (struct-out peer) (struct-out subnet)
|
||||
string->ip
|
||||
ip->string
|
||||
ip-netmask
|
||||
string->subnet
|
||||
subnet->string
|
||||
string->peer)
|
||||
|
||||
(require racket/struct)
|
||||
|
||||
(module+ test
|
||||
(require rackunit))
|
||||
|
||||
(struct peer [ip type]
|
||||
#:methods gen:custom-write
|
||||
[(define write-proc
|
||||
|
@ -37,6 +41,11 @@
|
|||
255)))))
|
||||
(string-join parts "."))
|
||||
|
||||
(define (ip-netmask ip)
|
||||
(for/sum ([i (in-range 32)])
|
||||
#:break (positive? (bitwise-and ip (arithmetic-shift 1 i)))
|
||||
1))
|
||||
|
||||
(define (string->subnet str)
|
||||
(match-define (list ipstr maskstr) (string-split str "/"))
|
||||
(subnet (string->ip ipstr)
|
||||
|
@ -44,9 +53,18 @@
|
|||
|
||||
(define (subnet->string sub)
|
||||
(format "~a/~a"
|
||||
(subnet-ip sub)
|
||||
(ip->string (subnet-ip sub))
|
||||
(subnet-mask sub)))
|
||||
|
||||
(define (string->peer str)
|
||||
(match-define (list ip type) (string-split str "-"))
|
||||
(peer (string->ip ip) (string->symbol type)))
|
||||
|
||||
;; ================================================================================
|
||||
|
||||
(module+ test
|
||||
(check-equal? (ip->string (string->ip "123.84.0.67")) "123.84.0.67")
|
||||
(check-equal? (ip->string (string->ip "0.0.0.0")) "0.0.0.0")
|
||||
|
||||
(check-equal? (ip-netmask (string->ip "255.255.254.0")) 9)
|
||||
(check-equal? (ip-netmask (string->ip "255.0.0.0")) 24))
|
||||
|
|
Loading…
Reference in New Issue