Added README file
[metux-java.git] / util / IPTools.java
blobd38eb81038f54016a3cf0585dbd0c32a92e18710
2 package org.de.metux.util;
4 import java.net.InetAddress;
5 import java.net.UnknownHostException;
7 import org.xbill.DNS.Lookup;
8 import org.xbill.DNS.SimpleResolver;
9 import org.xbill.DNS.Record;
10 import org.xbill.DNS.ARecord;
11 import org.xbill.DNS.Type;
13 public class IPTools
15 static public InetAddress getIP(String hostname, String server)
17 try
19 Lookup l = new Lookup(hostname,Type.A);
20 if (server!=null)
21 l.setResolver(new SimpleResolver(server));
23 l.run();
24 if (l.getResult()==Lookup.SUCCESSFUL)
26 Record res[] = l.getAnswers();
27 for (int x=0; x<res.length; x++)
29 ARecord arec = (ARecord)res[x];
30 return arec.getAddress();
33 else
34 return null;
36 catch (Exception e)
38 System.err.println("getIP() error: "+e);
39 return null;
42 return null;
45 static public InetAddress IPtoInetAddress(String ip)
47 try
49 InetAddress addr = InetAddress.getByName(ip);
50 return addr;
52 catch(Exception ex)
54 System.err.println("EX: "+ex);
55 return null;
59 static public InetAddress getInterfaceAddress(String ifname)
61 Exec e = new Exec();
63 // FIMXE !!!
64 String res = e.run_catch("/sbin/ifconfig "+ifname+" | grep \"inet addr\"");
65 if (res==null)
66 return null;
68 int pos_addr = res.indexOf("inet addr:");
69 int pos_mask = res.indexOf(" ",pos_addr+11);
71 String text_addr = res.substring(pos_addr+10,pos_mask).trim();
73 return IPtoInetAddress(text_addr);