Permalink
Browse files

created ifutil to get ipaddress correctly

  • Loading branch information...
alonswartz committed Sep 10, 2008
1 parent 244d064 commit 68a0137fad95ec9c0a1b53fdaf61d45147116869
Showing with 60 additions and 16 deletions.
  1. +1 −0 .gitignore
  2. +14 −16 config-console.py
  3. +45 −0 ifutil.py
View
@@ -0,0 +1 @@
+*.pyc
View
@@ -1,7 +1,8 @@
#!/usr/bin/python
import dialog
-import socket
+
+import ifutil
class Console:
def __init__(self, title=None, width=60, height=18):
@@ -16,32 +17,28 @@ def msgbox(self, title, text, button_label="ok"):
return self.console.msgbox(text, self.height, self.width,
title=title, ok_label=button_label)
-def _get_hostname():
- return socket.gethostname()
-
-def _get_ipaddr():
- #return "192.168.0.1"
- return None
-def _netstat():
+def _netservices():
+ #todo: get preferred ifname
#todo: check listening ports
- ipaddr = _get_ipaddr()
- if ipaddr:
- info = "Web Browser: http://%s\n" % ipaddr
- info += "Secure Shell: ssh root@%s\n" % ipaddr
- else:
- info = "Error: Network not configured\n"
+ ifname = 'eth1'
+ ipaddr = ifutil.get_ipinfo(ifname)[0]
+ if not ipaddr:
+ return "Error: %s interface not configured\n" % ifname
+
+ info = "Web Browser: http://%s\n" % ipaddr
+ info += "Secure Shell: ssh root@%s\n" % ipaddr
return info
def appname():
- return "Turnkey Linux %s" % _get_hostname().capitalize()
+ return "Turnkey Linux %s" % ifutil.get_hostname().capitalize()
def infotext(height):
header = "\nYou may access this %s appliance\n" % appname()
header += "over the network using the following methods:\n\n"
- body = _netstat()
+ body = _netservices()
footer = "For more information visit the Turnkey Linux Website\n"
footer += " http://www.turnkeylinux.org"
@@ -58,6 +55,7 @@ def main():
console = Console(title, width, height)
console.msgbox(appname(), infotext(height), button_label="Advanced")
+
if __name__ == "__main__":
main()
View
@@ -0,0 +1,45 @@
+
+import fcntl
+import struct
+import socket
+
+SIOCGIFADDR = 0x8915
+SIOCGIFNETMASK = 0x891b
+SIOCGIFBRDADDR = 0x8919
+
+class NIC:
+ class ATTRIBS:
+ ADDRS = {
+ 'addr': SIOCGIFADDR,
+ 'netmask': SIOCGIFNETMASK,
+ 'brdaddr': SIOCGIFBRDADDR,
+ }
+
+ def __init__(self, ifname):
+ self.ifname = ifname
+ self.ifreq = (self.ifname + '\0'*32)[:32]
+
+ def _get_addr(self, attrname):
+ try:
+ sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ result = fcntl.ioctl(sockfd.fileno(), attrname, self.ifreq)
+ except IOError:
+ return None
+
+ return socket.inet_ntoa(result[20:24])
+
+ def __getattr__(self, attrname):
+ if attrname in self.ATTRIBS.ADDRS:
+ return self._get_addr(self.ATTRIBS.ADDRS[attrname])
+
+
+# convenience functions
+
+def get_ipinfo(ifname):
+ nic = NIC(ifname)
+ return nic.addr, nic.netmask, nic.brdaddr
+
+def get_hostname():
+ return socket.gethostname()
+
+

0 comments on commit 68a0137

Please sign in to comment.