下面列出了org.bukkit.BanList#com.google.common.net.InetAddresses 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String readHost(ConsoleReader reader, PrintWriter out, String prompt) {
try {
String inputString = readInputString(reader, out, prompt);
if (InetAddresses.isInetAddress(inputString)) {
return inputString;
}
out.println("Error, " + inputString + " is not a valid inet address");
} catch (Exception exp) {
if (WorfCLI.verbose) {
exp.printStackTrace();
}
out.println("Error, unable to read the host. error=" + exp.getMessage());
}
return null;
}
@Test
public void resolveAll_nullResourceResolver() throws Exception {
final String hostname = "addr.fake";
final Inet4Address backendAddr = InetAddresses.fromInteger(0x7f000001);
AddressResolver mockResolver = mock(AddressResolver.class);
when(mockResolver.resolveAddress(Matchers.anyString()))
.thenReturn(Collections.<InetAddress>singletonList(backendAddr));
ResourceResolver resourceResolver = null;
boolean resovleSrv = true;
boolean resolveTxt = true;
ResolutionResults res = DnsNameResolver.resolveAll(
mockResolver, resourceResolver, resovleSrv, resolveTxt, hostname);
assertThat(res.addresses).containsExactly(backendAddr);
assertThat(res.balancerAddresses).isEmpty();
assertThat(res.txtRecords).isEmpty();
verify(mockResolver).resolveAddress(hostname);
}
private HostResource persistHostResource() throws Exception {
return persistResource(
new HostResource.Builder()
.setHostName(getUniqueIdFromCommand())
.setRepoId("1FF-FOOBAR")
.setPersistedCurrentSponsorClientId("my sponsor")
.setStatusValues(ImmutableSet.of(StatusValue.CLIENT_UPDATE_PROHIBITED))
.setInetAddresses(
ImmutableSet.of(
InetAddresses.forString("192.0.2.2"),
InetAddresses.forString("1080:0:0:0:8:800:200C:417A"),
InetAddresses.forString("192.0.2.29")))
.setPersistedCurrentSponsorClientId("TheRegistrar")
.setCreationClientId("NewRegistrar")
.setLastEppUpdateClientId("NewRegistrar")
.setCreationTimeForTest(DateTime.parse("1999-04-03T22:00:00.0Z"))
.setLastEppUpdateTime(DateTime.parse("1999-12-03T09:00:00.0Z"))
.setLastTransferTime(DateTime.parse("2000-04-08T09:00:00.0Z"))
.build());
}
/**
* Constructs an InterfaceAddress from a String of the form 1.2.3.4/25.
*
* @throws IllegalArgumentException if the argument was duff.
*/
@Nonnull
public static InterfaceAddress forString(@Nonnull String addressString) {
String netmaskString = null;
int idx = addressString.indexOf('/');
if (idx != -1) {
netmaskString = addressString.substring(idx + 1);
addressString = addressString.substring(0, idx);
}
InetAddress address = InetAddresses.forString(addressString);
int netmask;
if (netmaskString != null) {
try {
netmask = Integer.parseInt(netmaskString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Cannot parse netmask from " + netmaskString, e);
}
} else {
netmask = address.getAddress().length * Byte.SIZE;
}
return new InterfaceAddress(address, netmask);
}
@Override
public void verify(final Node node) {
final Map<String, Map<String, String>> result = node.execute(transaction);
assertThat(result.keySet())
.containsExactlyInAnyOrderElementsOf(Arrays.asList("p2p", "jsonrpc", "ws"));
assertThat(InetAddresses.isUriInetAddress(result.get("p2p").get("host"))).isTrue();
final int p2pPort = Integer.valueOf(result.get("p2p").get("port"));
assertThat(NetworkUtility.isValidPort(p2pPort)).isTrue();
assertThat(InetAddresses.isUriInetAddress(result.get("ws").get("host"))).isTrue();
final int wsPort = Integer.valueOf(result.get("ws").get("port"));
assertThat(NetworkUtility.isValidPort(wsPort)).isTrue();
assertThat(InetAddresses.isUriInetAddress(result.get("jsonrpc").get("host"))).isTrue();
final int jsonRpcPort = Integer.valueOf(result.get("jsonrpc").get("port"));
assertThat(NetworkUtility.isValidPort(jsonRpcPort)).isTrue();
}
@Override
public Collection<InetAddress> resolveRemapped(String remappedHost) {
// special case for IP literals: return the InetAddress without doing a dnsjava lookup. dnsjava seems to handle ipv4 literals
// reasonably well, but does not handle ipv6 literals (with or without [] brackets) correctly.
// note this does not work properly for ipv6 literals with a scope identifier, which is a known issue for InetAddresses.isInetAddress().
// (dnsjava also handles the situation incorrectly)
if (InetAddresses.isInetAddress(remappedHost)) {
return Collections.singletonList(InetAddresses.forString(remappedHost));
}
// retrieve IPv4 addresses, then retrieve IPv6 addresses only if no IPv4 addresses are found. the current implementation always uses the
// first returned address, so there is no need to look for IPv6 addresses if an IPv4 address is found.
Collection<InetAddress> ipv4addresses = resolveHostByType(remappedHost, Type.A);
if (!ipv4addresses.isEmpty()) {
return ipv4addresses;
} else {
return resolveHostByType(remappedHost, Type.AAAA);
}
}
public static List<InetAddress> toInetAddressList(List<String> addressList) {
if (CollectionUtils.isEmpty(addressList)) {
return Collections.emptyList();
}
final List<InetAddress> inetAddressList = new ArrayList<InetAddress>(addressList.size());
for (String ignoreAddress : addressList) {
if (StringUtils.isBlank(ignoreAddress)) {
continue;
}
// not throw UnknownHostException
final InetAddress address = InetAddresses.forString(ignoreAddress);
if (address != null) {
inetAddressList.add(address);
}
}
return inetAddressList;
}
@Override
public Collection<InetAddress> resolveRemapped(String remappedHost) {
// special case for IP literals: return the InetAddress without doing a dnsjava lookup. dnsjava seems to handle ipv4 literals
// reasonably well, but does not handle ipv6 literals (with or without [] brackets) correctly.
// note this does not work properly for ipv6 literals with a scope identifier, which is a known issue for InetAddresses.isInetAddress().
// (dnsjava also handles the situation incorrectly)
if (InetAddresses.isInetAddress(remappedHost)) {
return Collections.singletonList(InetAddresses.forString(remappedHost));
}
// retrieve IPv4 addresses, then retrieve IPv6 addresses only if no IPv4 addresses are found. the current implementation always uses the
// first returned address, so there is no need to look for IPv6 addresses if an IPv4 address is found.
Collection<InetAddress> ipv4addresses = resolveHostByType(remappedHost, Type.A);
if (!ipv4addresses.isEmpty()) {
return ipv4addresses;
} else {
return resolveHostByType(remappedHost, Type.AAAA);
}
}
/**
* Tests valueOf() converter for IPv4 InetAddress.
*/
@Test
public void testValueOfInetAddressIPv4() {
IpAddress ipAddress;
InetAddress inetAddress;
inetAddress = InetAddresses.forString("1.2.3.4");
ipAddress = IpAddress.valueOf(inetAddress);
assertThat(ipAddress.toString(), is("1.2.3.4"));
inetAddress = InetAddresses.forString("0.0.0.0");
ipAddress = IpAddress.valueOf(inetAddress);
assertThat(ipAddress.toString(), is("0.0.0.0"));
inetAddress = InetAddresses.forString("255.255.255.255");
ipAddress = IpAddress.valueOf(inetAddress);
assertThat(ipAddress.toString(), is("255.255.255.255"));
}
/**
* Get the IPv6 address for the host if any.
*
* @throws ConvergenceException if multiple addresses are found
*/
default Optional<Inet6Address> getIPv6Address(String hostname) {
List<Inet6Address> ipv6addresses = Stream.of(getAddresses(hostname))
.filter(Inet6Address.class::isInstance)
.filter(inetAddress -> !inetAddress.isLoopbackAddress())
.map(Inet6Address.class::cast)
.filter(inetAddress -> !inetAddress.isLinkLocalAddress())
.filter(inetAddress -> !inetAddress.isSiteLocalAddress())
.collect(Collectors.toList());
if (ipv6addresses.size() <= 1) return ipv6addresses.stream().findFirst();
String addresses = ipv6addresses.stream().map(InetAddresses::toAddrString).collect(Collectors.joining(","));
throw new ConvergenceException(
String.format(
"Multiple IPv6 addresses found: %s. Perhaps a missing DNS entry or multiple AAAA records in DNS?",
addresses));
}
public InetAddress getIp(final UUID uuid) {
ProxiedPlayer player = plugin.getProxy().getPlayer(uuid);
if (player != null)
return player.getAddress().getAddress();
try {
return ipCache.get(uuid, new Callable<InetAddress>() {
@Override
public InetAddress call() throws Exception {
try (Jedis tmpRsc = plugin.getPool().getResource()) {
String result = tmpRsc.hget("player:" + uuid, "ip");
if (result == null)
throw new NullPointerException("user not found");
return InetAddresses.forString(result);
}
}
});
} catch (ExecutionException | UncheckedExecutionException e) {
if (e.getCause() instanceof NullPointerException && e.getCause().getMessage().equals("user not found"))
return null; // HACK
plugin.getLogger().log(Level.SEVERE, "Unable to get IP", e);
throw new RuntimeException("Unable to get IP for " + uuid, e);
}
}
public VersionMessage(NetworkParameters params, int newBestHeight) {
super(params);
clientVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.CURRENT);
localServices = 0;
time = System.currentTimeMillis() / 1000;
// Note that the Bitcoin Core doesn't do anything with these, and finding out your own external IP address
// is kind of tricky anyway, so we just put nonsense here for now.
InetAddress localhost = InetAddresses.forString("127.0.0.1");
myAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
theirAddr = new PeerAddress(params, localhost, params.getPort(), 0, BigInteger.ZERO);
subVer = LIBRARY_SUBVER;
bestHeight = newBestHeight;
relayTxesBeforeFilter = true;
length = 85;
if (protocolVersion > 31402)
length += 8;
length += VarInt.sizeOf(subVer.length()) + subVer.length();
}
private static HostResource makeHostResource(
FakeClock clock, String repoId, String fqhn, String ip) {
clock.advanceOneMilli();
return persistEppResource(
new HostResource.Builder()
.setCreationClientId("LawyerCat")
.setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
.setPersistedCurrentSponsorClientId("BusinessCat")
.setHostName(Idn.toASCII(fqhn))
.setInetAddresses(ImmutableSet.of(InetAddresses.forString(ip)))
.setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
.setLastEppUpdateClientId("CeilingCat")
.setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
.setRepoId(repoId)
.setStatusValues(ImmutableSet.of(StatusValue.OK))
.build());
}
static HostResource makeHostResource(FakeClock clock, String fqhn, String ip) {
clock.advanceOneMilli();
return persistResourceWithCommitLog(
new HostResource.Builder()
.setRepoId(generateNewContactHostRoid())
.setCreationClientId("LawyerCat")
.setCreationTimeForTest(clock.nowUtc())
.setPersistedCurrentSponsorClientId("BusinessCat")
.setHostName(Idn.toASCII(fqhn))
.setInetAddresses(ImmutableSet.of(InetAddresses.forString(ip)))
.setLastTransferTime(DateTime.parse("1990-01-01T00:00:00Z"))
.setLastEppUpdateClientId("CeilingCat")
.setLastEppUpdateTime(clock.nowUtc())
.setStatusValues(ImmutableSet.of(StatusValue.OK))
.build());
}
@Test
public void testMarshal() throws Exception {
// Bean! Bean! Bean!
XjcRdeHostElement bean =
HostResourceToXjcConverter.convertExternal(
new HostResource.Builder()
.setCreationClientId("LawyerCat")
.setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
.setPersistedCurrentSponsorClientId("BusinessCat")
.setHostName("ns1.love.lol")
.setInetAddresses(ImmutableSet.of(InetAddresses.forString("cafe::abba")))
.setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
.setLastEppUpdateClientId("CeilingCat")
.setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
.setRepoId("2-LOL")
.setStatusValues(ImmutableSet.of(StatusValue.OK))
.build());
marshalStrict(bean, new ByteArrayOutputStream(), UTF_8);
}
@Test
public void testConvertExternalHost_ipv6() {
XjcRdeHost bean =
HostResourceToXjcConverter.convertExternalHost(
new HostResource.Builder()
.setCreationClientId("LawyerCat")
.setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z"))
.setPersistedCurrentSponsorClientId("BusinessCat")
.setHostName("ns1.love.lol")
.setInetAddresses(ImmutableSet.of(InetAddresses.forString("cafe::abba")))
.setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z"))
.setLastEppUpdateClientId("CeilingCat")
.setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z"))
.setRepoId("2-LOL")
.setStatusValues(ImmutableSet.of(StatusValue.OK))
.build());
assertThat(bean.getAddrs()).hasSize(1);
assertThat(bean.getAddrs().get(0).getIp().value()).isEqualTo("v6");
assertThat(bean.getAddrs().get(0).getValue()).isEqualTo("cafe::abba");
}
private static String readInteger(ConsoleReader reader, PrintWriter out, String prompt) {
try {
String inputString = readInputString(reader, out, prompt);
if (NumberUtils.isNumber(inputString)) {
return inputString;
}
if (InetAddresses.isInetAddress(inputString)) {
return inputString;
}
out.println("Error, " + inputString + " is not a number");
} catch (Exception exp) {
if (WorfCLI.verbose) {
exp.printStackTrace();
}
out.println("Error, unable to read the host. error=" + exp.getMessage());
}
return null;
}
/** Utility: Sets the ServerIdentifier option in the reply. */
protected static void setServerIdentifier(
@Nonnull DhcpMessage reply,
@Nonnull InetAddress localAddress) {
if (!AddressUtils.isZeroAddress(localAddress)) {
reply.setServerHostname(InetAddresses.toAddrString(localAddress));
reply.getOptions().add(new ServerIdentifier(localAddress));
}
}
@VisibleForTesting
static SocketAddress pickAddressInternal(Server chosenServer, @Nullable String connPoolConfigOriginName) {
String rawHost;
int port;
if (chosenServer instanceof DiscoveryEnabledServer) {
DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) chosenServer;
// Configuration for whether to use IP address or host has already been applied in the
// DiscoveryEnabledServer constructor.
rawHost = discoveryServer.getHost();
port = discoveryServer.getPort();
} else {
// create mock instance info for non-discovery instances
rawHost = chosenServer.getHost();
port = chosenServer.getPort();
}
InetSocketAddress serverAddr;
try {
InetAddress ipAddr = InetAddresses.forString(rawHost);
serverAddr = new InetSocketAddress(ipAddr, port);
} catch (IllegalArgumentException e1) {
LOG.warn("NettyClientConnectionFactory got an unresolved address, addr: {}", rawHost);
Counter unresolvedDiscoveryHost = SpectatorUtils.newCounter(
"unresolvedDiscoveryHost",
connPoolConfigOriginName == null ? "unknownOrigin" : connPoolConfigOriginName);
unresolvedDiscoveryHost.increment();
try {
serverAddr = new InetSocketAddress(rawHost, port);
} catch (RuntimeException e2) {
e1.addSuppressed(e2);
throw e1;
}
}
return serverAddr;
}
@Before
public void setUp() throws Exception {
endpoints = ImmutableList.of(
endpoint(new URI("https://server1.example"), InetAddresses.forString("192.168.0.1")),
endpoint(new URI("https://server2.example"), InetAddresses.forString("192.168.0.2"))
);
}
@Test
public void negotiateProxy_ppv1_ipv4() {
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true));
ByteBuf buf = Unpooled.wrappedBuffer(
"PROXY TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII));
channel.writeInbound(buf);
Object dropped = channel.readInbound();
assertNull(dropped);
// The handler should remove itself.
assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME));
assertNull(channel.pipeline().context(HAProxyMessageChannelHandler.class));
assertEquals(HAProxyProtocolVersion.V1, channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get());
// TODO(carl-mastrangelo): this check is in place, but it should be removed. The message is not properly GC'd
// in later versions of netty.
assertNotNull(channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get());
assertEquals("124.123.111.111", channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get());
assertEquals(
new InetSocketAddress(InetAddresses.forString("124.123.111.111"), 443),
channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get());
assertEquals(Integer.valueOf(443), channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_PORT).get());
assertEquals("192.168.0.1", channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get());
assertEquals(Integer.valueOf(10008), channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_PORT).get());
assertEquals(
new InetSocketAddress(InetAddresses.forString("192.168.0.1"), 10008),
channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get());
}
/**
* Encodes this endpoint to an RLP representation that is inlined into a containing object
* (generally a Peer).
*
* @param out The RLP output stream.
*/
public void encodeInline(final RLPOutput out) {
out.writeInetAddress(InetAddresses.forString(host));
out.writeUnsignedShort(udpPort);
if (tcpPort.isPresent()) {
out.writeUnsignedShort(tcpPort.getAsInt());
} else {
out.writeNull();
}
}
public URI toURIWithoutDiscoveryPort() {
final String uri =
String.format(
"enode://%[email protected]%s:%d",
nodeId.toUnprefixedHexString(),
InetAddresses.toUriString(ip),
getListeningPortOrZero());
return URI.create(uri);
}
public Builder ipAddress(final String ip) {
if (InetAddresses.isUriInetAddress(ip)) {
this.ip = InetAddresses.forUriString(ip);
} else if (InetAddresses.isInetAddress(ip)) {
this.ip = InetAddresses.forString(ip);
} else {
throw new IllegalArgumentException("Invalid ip address.");
}
return this;
}
@Test
public void createFromIpv6URI() {
final Peer peer =
DefaultPeer.fromURI(
"enode://c7849b663d12a2b5bf05b1ebf5810364f4870d5f1053fbd7500d38bc54c705b45[email protected][2001:0DB8:85A3:0000::8A2E:370:7334]:30403");
assertThat(peer.getId())
.isEqualTo(
fromHexString(
"c7849b663d12a2b5bf05b1ebf5810364f4870d5f1053fbd7500d38bc54c705b453d7511ca8a4a86003d34d4c8ee0bbfcd387aa724f5b240b3ab4bbb994a1e09b"));
assertThat(peer.getEnodeURL().getIp())
.isEqualTo(InetAddresses.forString("2001:db8:85a3::8a2e:370:7334"));
assertThat(peer.getEnodeURL().getListeningPortOrZero()).isEqualTo(30403);
assertThat(peer.getEnodeURL().getDiscoveryPortOrZero()).isEqualTo(30403);
}
/**
* Converts an IPv6 string literal (e.g., "1111:2222::8888") into an IP
* address.
*
* @param value an IPv6 address value in string form
* @return an IPv6 address
* @throws IllegalArgumentException if the argument is invalid
*/
public static AtriumIp6Address valueOf(String value) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddresses.forString(value);
} catch (IllegalArgumentException e) {
final String msg = "Invalid IP address string: " + value;
throw new IllegalArgumentException(msg);
}
return valueOf(inetAddress);
}
private void setOpenFlowNodeRef(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder, Bridge bridge) {
Map<UUID, Controller> updatedControllerRows =
TyperUtils.extractRowsUpdated(Controller.class, getUpdates(), getDbSchema());
LOG.debug("setOpenFlowNodeRef: updatedControllerRows: {}", updatedControllerRows);
for (ControllerEntry controllerEntry: SouthboundMapper.createControllerEntries(bridge, updatedControllerRows)) {
if (controllerEntry != null
&& controllerEntry.isIsConnected() != null && controllerEntry.isIsConnected()) {
String [] controllerTarget = controllerEntry.getTarget().getValue().split(":");
IpAddress bridgeControllerIpAddress = null;
for (String targetElement : controllerTarget) {
if (InetAddresses.isInetAddress(targetElement)) {
bridgeControllerIpAddress = IpAddressBuilder.getDefaultInstance(targetElement);
continue;
}
if (NumberUtils.isCreatable(targetElement)) {
continue;
}
}
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
networkInterfacesLoop:
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> networkInterfaceAddresses = networkInterface.getInetAddresses();
while (networkInterfaceAddresses.hasMoreElements()) {
InetAddress networkInterfaceAddress = networkInterfaceAddresses.nextElement();
if (bridgeControllerIpAddress.getIpv4Address().getValue()
.equals(networkInterfaceAddress.getHostAddress())) {
ovsdbBridgeAugmentationBuilder.setBridgeOpenflowNodeRef(
getOvsdbConnectionInstance().getInstanceIdentifier());
break networkInterfacesLoop;
}
}
}
} catch (SocketException e) {
LOG.warn("Error getting local ip address", e);
}
}
}
}
@Override
protected String toStringData() throws DhcpException {
StringBuilder buf = new StringBuilder("[");
for (InetAddress address : getAddresses())
buf.append(" ").append(InetAddresses.toAddrString(address));
buf.append(" ]");
return buf.toString();
}
/**
* Retrieve tokens representing the host of the given URL
* @param url URL to be tokenized
* @param partStringRaw raw (not url decoded) string containing the host
* @param partString potentially url decoded string containing the host
* @return host tokens
* @throws IOException
*/
private List<Token> getHostTokens(String url, String partStringRaw, String partString) throws IOException {
int start = getStartIndex(url, partStringRaw);
if (!tokenizeHost || InetAddresses.isInetAddress(partString)) {
int end = getEndIndex(start, partStringRaw);
return Collections.singletonList(new Token(partString, URLPart.HOST, start, end));
}
return tokenize(URLPart.HOST, addReader(new ReversePathHierarchyTokenizer('.', '.'), new StringReader(partString)), start);
}
@Override
public AddressShim marshal(InetAddress inetAddress) {
AddressShim shim = new AddressShim();
shim.ipAddress = InetAddresses.toAddrString(inetAddress);
shim.ipVersion = (inetAddress instanceof Inet6Address) ? "v6" : "v4";
return shim;
}