View Javadoc

1   /*
2    * $Id: GetHostnameTask.java,v 1.1 2004/09/10 18:26:26 pah Exp $
3    * 
4    * Created on 10-Sep-2004 by Paul Harrison (pah@jb.man.ac.uk)
5    * Copyright 2004 AstroGrid. All rights reserved.
6    *
7    * This software is published under the terms of the AstroGrid 
8    * Software License version 1.2, a copy of which has been included 
9    * with this distribution in the LICENSE.txt file.  
10   *
11   */ 
12  
13  package org.astrogrid.deployment;
14  
15  import java.net.InetAddress;
16  import java.net.UnknownHostException;
17  
18  import org.apache.tools.ant.BuildException;
19  import org.apache.tools.ant.Task;
20  
21  /***
22   * Ant task to find the full hostname. This should hopefully work on unix and
23   * windows, better than trying to rely on environment variables.
24   * 
25   * @author Paul Harrison (pah@jb.man.ac.uk) 10-Sep-2004
26   * @version $Name:  $
27   * @since iteration6
28   */
29  public class GetHostnameTask extends Task {
30  
31      private boolean ip = false;
32      /***
33       *  
34       */
35      public GetHostnameTask() {
36          super();
37         
38      }
39      
40      public void execute() throws BuildException  {
41         
42              try {
43                  InetAddress addr = InetAddress.getLocalHost();
44                  String hostname = "";
45                  if (ip) {
46                      byte[] raw = addr.getAddress();
47                      for (int i = 0; i < raw.length; i++) {
48                          int b = (int)raw[i];
49                          if (b < 0)
50                              b += 256;
51                          hostname += String.valueOf(b);
52                          if (i < raw.length - 1)
53                              hostname += ".";
54                      }
55                  }
56                  else {
57                      hostname = addr.getCanonicalHostName();
58                  }
59                  getProject().setUserProperty("astrogrid.hostname", hostname);
60              }
61              catch (UnknownHostException e) {
62                 throw new BuildException("cannot get the hostname", e );
63              }
64          }
65           /***
66            * set this to true to make the output a pure ip address rather than the dns name.
67           * @param ip
68           */
69          public void setIp(boolean ip) {
70          this.ip = ip;
71      }
72  }
73  
74      
75