ambrevar: Add network interface parsing functions.

master
Pierre Neidhardt 2020-12-20 12:12:45 +01:00
parent a36dc9bb51
commit bd635099b8
1 changed files with 31 additions and 0 deletions

View File

@ -263,3 +263,34 @@ different Btrfs subvolumes."
;; character, like "\\[".
(uiop:native-namestring source)
(uiop:native-namestring destination))))
(defun loopback? (interface)
(or (string= "link/loopback" (first (second interface)))
(string= "lo:" (second (first interface)))))
(defun ipv4 (interface)
(when (string= "inet" (first (third interface)))
(ppcre:regex-replace "/.*" (second (third interface)) "")))
;; TODO: Make class for interfaces? Can iolib / usocket be helpful here?
(defun interfaces (&optional interface)
"Return IP of current INTERFACE.
INTERFACE is a string in the form of `wlp2s0'."
(let* ((raw-list (tokenize (run* "ip" "address" interface))))
(sera:collecting
(sera:do-splits ((l r) (raw-list (lambda (line)
(ppcre:scan "[0-9]+:" (first line)))))
(sera:and-let* ((split (subseq raw-list (max 0 (1- l)) r)))
(collect split))))))
(defun interfaces-with-ipv4 ()
"Return list of interfaces with ipv4, excluding the loopback."
(remove-if (complement #'ipv4)
(remove-if #'loopback? (interfaces))))
(defun current-interface ()
(first (interfaces-with-ipv4)))
(export-always 'current-ip)
(defun current-ip ()
(ipv4 (default-interface)))