Posted By

djharuko on 05/07/10


system utilities

Versions (?)

Get IP addresses of system

 / Published in: Emacs Lisp

A quick hack I made up. I wanted a platform agnostic way to get the IP addresses of the system I was on. Tested under Linux and Windows. Can be expanded to accommodate more systems.

Takes no arguments and returns a list of strings.

  1. (defun get-ip-addresses ()
  2. "Returns the current system IPv4 addresses as a list of
  3. strings"
  4. (let* ((start 0)
  5. ; (match-positions ())
  6. (ip-re "[1-9][0-9]?[0-9]?\.[1-9][0-9]?[0-9]?\.[1-9][0-9]?[0-9]?\.[1-9][0-9]?[0-9]?")
  7. ;; The rest of these variables try to make this platform agnostic.
  8. ;; Add more on to the cond statements if you need
  9. (ipconfig (cond ((eq system-type 'windows-nt)
  10. "ipconfig")
  11. ((eq system-type 'gnu/linux)
  12. "/sbin/ifconfig")
  13. (t (error "Don't know how to get-ip-address for %s"
  14. system-type))))
  15. (line-re (cond ((eq system-type 'windows-nt)
  16. "IPv4 Address.*")
  17. ((eq system-type 'gnu/linux)
  18. (concat "inet addr:" ip-re))
  19. (t (error "Don't know how regex out ip line for %s"
  20. system-type))))
  21. ;; I lied, not all of the rest of the variables are to make it
  22. ;; platform agnostic. This is where we grab the output
  23. (output (shell-command-to-string ipconfig)))
  25. ;; The inner loop is a bit funky since I can't seem to get it to behave
  26. ;; exactly like Common Lisp
  27. (loop for pos in
  28. (loop named inner
  29. with match-positions = ()
  30. do (let ((ret (string-match line-re output start)))
  31. (if ret
  32. (setq start (1+ ret))
  33. (return-from inner match-positions))
  34. (setq match-positions
  35. (append match-positions (list ret)))))
  36. collect (progn
  37. (string-match ip-re output pos)
  38. (match-string 0 output)))))

Report this snippet  

You need to login to post a comment.