简体   繁体   中英

java.lang.NumberFormatException in System Groovy script

def ipadd = addr.hostAddress
//println ipadd
String myString = new Integer(ipadd);
def pa = new ParametersAction([new StringParameterValue('IPADDR', myString)]);  
Thread.currentThread().executable.addAction(pa) 
println 'Script finished! \n';

I am trying to save the ip address of the slave by adding it to System variable and pass it to next job.But when I run the job , I am getting below exception : Logs :

Slave Machine 2: X.X.X.X
java.lang.NumberFormatException: For input string: "X.X.X.X"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.<init>(Integer.java:867)

An IPv4 address contains 3 dots in it, so it cannot be directly parsed as an Integer .

I suppose you are trying to convert it to the corresponding int representing the IP 32 bits. This can be done in Java like this:

public static int ipToInt32(String ip) {
    Inet4Address ipAddress;
    try {
        ipAddress = (Inet4Address) InetAddress.getByName(ip);
    } catch (UnknownHostException e) {
        throw new IllegalStateException("Cannot convert IP to bits: '" + ip + "'", e);
    }
    byte[] ipBytes = ipAddress.getAddress();
    return ((ipBytes[0] & 0xFF) << 24)
            | ((ipBytes[1] & 0xFF) << 16)
            | ((ipBytes[2] & 0xFF) << 8)
            | (ipBytes[3] & 0xFF);
}

You cannot cast the ipadd to an integer. Because it is not a valid integer. As I see it there is no mandatory need for you to cast the ipadd to an integer. Therefore my recommendation is to replace the line String myString = new Integer(ipadd) with following line.

String myString = new String(ipadd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM