i need to increment ip addresses for a little proof of concept thing i am doing. im using java for this cuz it makes socket programming easy. the constructors for sockets all accept strings for ip addresses so here is what i came up with. there are other ways im sure. i know of one converting the ip as a polynomial of 256 and so forth but anyway, here is what i tossed together. if anyone has a more elegant solution, please chime in.
public String incrementIp(String s){
int[] octet = new int[4];
int i=0;
StringTokenizer st=new StringTokenizer(s,".");
while(st.hasMoreTokens()&&i<4){
octet[i]=Integer.parseInt(st.nextToken());
i++;
}
octet[3]+=1;
if(octet[3]>254){
octet[3]=1;
octet[2]+=1;
}
if(octet[2]>254){
octet[2]=1;
octet[1]+=1;
}
s=new String(octet[0] + "." + octet[1] + "." + octet[2]
+ "." + octet[3]);
return s;
}
public String incrementIp(String s){
int[] octet = new int[4];
int i=0;
StringTokenizer st=new StringTokenizer(s,".");
while(st.hasMoreTokens()&&i<4){
octet[i]=Integer.parseInt(st.nextToken());
i++;
}
octet[3]+=1;
if(octet[3]>254){
octet[3]=1;
octet[2]+=1;
}
if(octet[2]>254){
octet[2]=1;
octet[1]+=1;
}
s=new String(octet[0] + "." + octet[1] + "." + octet[2]
+ "." + octet[3]);
return s;
}


Comment