Я пытался реализовать пользовательский конструктор с помощью StringBuilder для строковых операций. Надеюсь, это поможет вам.
Пользовательский класс
public class Address {
@SuppressWarnings("unused")
private static final long serialVersionUID = 1L;
String ip;
Address(String ip) {
this.ip = ip;
}
boolean isLinkLocal() throws UnknownHostException{
return getInet6Address().isLinkLocalAddress();
}
@SuppressWarnings("static-access")
Inet6Address getInet6Address() throws UnknownHostException {
return (Inet6Address) Inet6Address.getByName(getIp());
}
String getIp() {
return this.ip;
}
}
Builder
public class AddressBuilder {
private String mac1;
private String mac2;
private String mac3;
private String mac4;
private String mac5;
private String mac6;
private String ipv6_2;
private String ipv6_3;
private String ipv6_4;
private String ipv6;
private static final String IPV6_1 = "fe80";
private static final String FF_FE = "ff:fe";
private static final String DOTS = "ff:fe";
public AddressBuilder () { }
AddressBuilder setMac(String mac){
String[] splittedMac = mac.split(":");
this.mac1 = splittedMac[0];
this.mac2 = splittedMac[1];
this.mac3 = splittedMac[2];
this.mac4 = splittedMac[3];
this.mac5 = splittedMac[4];
this.mac6 = splittedMac[5];
return this;
}
AddressBuilder throwFffeAndReformatToIPv6Notation() {
StringBuilder sb = new StringBuilder();
this.ipv6 = sb
.append(mac1)
.append(mac2)
.append(DOTS)
.append(mac3)
.append(FF_FE)
.append(mac4)
.append(DOTS)
.append(mac5)
.append(mac6)
.toString();
String[] splittedIPv6 = this.ipv6.split(":");
this.ipv6_2 = splittedIPv6[0];
this.ipv6_3 = splittedIPv6[1];
this.ipv6_4 = splittedIPv6[2];
return this;
}
AddressBuilder convertFirstOctetFromHexToBinaryAndReplaceIt() {
char[] binaryString = Integer.toBinaryString(Integer.parseInt(this.ipv6_2.substring(0, 2))).toCharArray();
Integer binaryStringInverted = Integer.parseUnsignedInt(Character.toString(binaryString[5])) == 0 ? 1 : 0;
binaryString[5] = binaryStringInverted.toString().toCharArray()[0];
this.ipv6_2 = new String(binaryString);
return this;
}
AddressBuilder prependLocalLinkPrefix() {
StringBuilder sb = new StringBuilder();
this.ipv6 = sb
.append(IPV6_1)
.append(DOTS)
.append(ipv6_2)
.append(DOTS)
.append(ipv6_3)
.append(DOTS)
.append(ipv6_4)
.toString();
return this;
}
Address build(){
return new Address(this.ipv6);
}
}
Пример использования
String mac = "52:74:f2:b1:a8:7f";
AddressBuilder ad = new AddressBuilder();
Address address = ad
.setMac(mac)
.throwFffeAndReformatToIPv6Notation()
.convertFirstOctetFromHexToBinaryAndReplaceIt()
.prependLocalLinkPrefix()
.build();
try {
System.out.println("is Link local? "+address.isLinkLocal());
} catch (UnknownHostException uhe) {
System.out.println("is Link local? no");
}