01: /*
02: * @(#)getInetAddress.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.Context;
12: import pnuts.lang.PnutsFunction;
13: import pnuts.lang.PnutsException;
14: import java.net.InetAddress;
15: import java.net.UnknownHostException;
16: import java.util.StringTokenizer;
17:
18: public class getInetAddress extends PnutsFunction {
19:
20: public getInetAddress() {
21: super ("getInetAddress");
22: }
23:
24: public boolean defined(int nargs) {
25: return nargs == 1 || nargs == 2;
26: }
27:
28: static InetAddress getInetAddress(String hostName, String address)
29: throws UnknownHostException {
30: StringTokenizer st = new StringTokenizer(address, ".");
31: if (st.countTokens() == 4) {
32: try {
33: byte[] bytes = new byte[4];
34: for (int i = 0; i < 4; i++) {
35: bytes[i] = (byte) Integer.parseInt(st.nextToken());
36: }
37: if (hostName != address) {
38: return InetAddress.getByAddress(hostName, bytes);
39: } else {
40: return InetAddress.getByAddress(bytes);
41: }
42: } catch (NumberFormatException num) {
43: return InetAddress.getByName(hostName);
44: }
45: } else {
46: return InetAddress.getByName(hostName);
47: }
48: }
49:
50: protected Object exec(Object[] args, Context context) {
51: int nargs = args.length;
52: try {
53: if (nargs == 1) {
54: Object hostOrAddr = args[0];
55: if (hostOrAddr instanceof InetAddress) {
56: return (InetAddress) hostOrAddr;
57: } else if (hostOrAddr instanceof String) {
58: String s = (String) hostOrAddr;
59: return getInetAddress(s, s);
60: } else {
61: throw new IllegalArgumentException(String
62: .valueOf(hostOrAddr));
63: }
64: } else if (nargs == 2) {
65: String host = (String) args[0];
66: String addr = (String) args[1];
67: return getInetAddress(host, addr);
68: } else {
69: undefined(args, context);
70: return null;
71: }
72: } catch (UnknownHostException e) {
73: throw new PnutsException(e, context);
74: }
75: }
76:
77: public String toString() {
78: return "function getInetAddress(host, addr) or (hostOrAddr)";
79: }
80: }
|