Java Code Examples for com.google.common.net.InetAddresses#forString()

The following examples show how to use com.google.common.net.InetAddresses#forString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateHostCommand.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
protected void initMutatingEppToolCommand() {
  setSoyTemplate(HostCreateSoyInfo.getInstance(), HostCreateSoyInfo.HOSTCREATE);
  ImmutableList.Builder<String> ipv4Addresses = new ImmutableList.Builder<>();
  ImmutableList.Builder<String> ipv6Addresses = new ImmutableList.Builder<>();
  for (String address : nullToEmpty(addresses)) {
    InetAddress inetAddress = InetAddresses.forString(address);
    if (inetAddress instanceof Inet4Address) {
      ipv4Addresses.add(inetAddress.getHostAddress());
    } else if (inetAddress instanceof Inet6Address) {
      ipv6Addresses.add(inetAddress.getHostAddress());
    } else {
      throw new IllegalArgumentException(
          String.format("IP address in unknown format: %s", address));
    }
  }
  addSoyRecord(
      clientId,
      new SoyMapData(
          "hostname", hostName,
          "ipv4addresses", ipv4Addresses.build(),
          "ipv6addresses", ipv6Addresses.build()));
}
 
Example 2
Source File: InetAddressType.java    From hibernate-postgresql with Apache License 2.0 5 votes vote down vote up
@Override
 public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor sessionImplementor, Object owner) throws HibernateException, SQLException {
	if (names.length != 1)
		throw new IllegalArgumentException("names.length != 1, names = " + names);

	String value = resultSet.getString(names[0]);

	if (value == null) {
		return null;
	} else {
		return InetAddresses.forString(value);
	}
}
 
Example 3
Source File: DeleteNodeRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    nodeIp = in.readString();
    nodePort = in.readInt();
    this.address = InetAddresses.forString(nodeIp);
}
 
Example 4
Source File: TlsCredentials.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static InetAddress parseInetAddress(String asciiAddr) {
  try {
    return InetAddresses.forString(HostAndPort.fromString(asciiAddr).getHost());
  } catch (IllegalArgumentException e) {
    return null;
  }
}
 
Example 5
Source File: NetworkSetTest.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testNetworkSetRemove() throws Exception {
    NetworkSet set = new NetworkSet();
    addRange(set, "0.0.0.0", "255.255.255.255");
    InetAddress address = InetAddresses.forString("1.2.3.4");
    set.removeAddress(address);
    set.removeNetwork(NetworkAddress.forString("123.45.6.7/25"));
    assertSize(set, 54);
    for (NetworkAddress network : set.toNetworkList())
        assertFalse("Network " + network + " should not contain " + address, network.contains(address));
}
 
Example 6
Source File: AtriumIpAddress.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an IPv4 or IPv6 string literal (e.g., "10.2.3.4" or
 * "1111:2222::8888") into an IP address.
 *
 * @param value an IP address value in string form
 * @return an IP address
 * @throws IllegalArgumentException if the argument is invalid
 */
public static AtriumIpAddress 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);
}
 
Example 7
Source File: DockerOperationsImplTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyEtcHosts() {
    ContainerData containerData = mock(ContainerData.class);
    String hostname = "hostname";
    InetAddress ipV6Local = InetAddresses.forString("::1");
    InetAddress ipV4Local = InetAddresses.forString("127.0.0.1");

    dockerOperations.addEtcHosts(containerData, hostname, Optional.empty(), Optional.of(ipV6Local));

    verify(containerData, times(1)).addFile(
            fileSystem.getPath("/etc/hosts"),
            "# This file was generated by com.yahoo.vespa.hosted.node.admin.docker.DockerOperationsImpl\n" +
                    "127.0.0.1	localhost\n" +
                    "::1	localhost ip6-localhost ip6-loopback\n" +
                    "fe00::0	ip6-localnet\n" +
                    "ff00::0	ip6-mcastprefix\n" +
                    "ff02::1	ip6-allnodes\n" +
                    "ff02::2	ip6-allrouters\n" +
                    "0:0:0:0:0:0:0:1	hostname\n");

    dockerOperations.addEtcHosts(containerData, hostname, Optional.of(ipV4Local), Optional.of(ipV6Local));

    verify(containerData, times(1)).addFile(
            fileSystem.getPath("/etc/hosts"),
            "# This file was generated by com.yahoo.vespa.hosted.node.admin.docker.DockerOperationsImpl\n" +
                    "127.0.0.1	localhost\n" +
                    "::1	localhost ip6-localhost ip6-loopback\n" +
                    "fe00::0	ip6-localnet\n" +
                    "ff00::0	ip6-mcastprefix\n" +
                    "ff02::1	ip6-allnodes\n" +
                    "ff02::2	ip6-allrouters\n" +
                    "0:0:0:0:0:0:0:1	hostname\n" +
                    "127.0.0.1	hostname\n");
}
 
Example 8
Source File: RdapNameserverSearchAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the parameters and calls the appropriate search function.
 *
 * <p>The RDAP spec allows nameserver search by either name or IP address.
 */
@Override
public NameserverSearchResponse getSearchResponse(boolean isHeadRequest) {
  // RDAP syntax example: /rdap/nameservers?name=ns*.example.com.
  if (Booleans.countTrue(nameParam.isPresent(), ipParam.isPresent()) != 1) {
    throw new BadRequestException("You must specify either name=XXXX or ip=YYYY");
  }
  NameserverSearchResponse results;
  if (nameParam.isPresent()) {
    // RDAP Technical Implementation Guilde 2.2.3 - we MAY support nameserver search queries based
    // on a "nameserver search pattern" as defined in RFC7482
    //
    // syntax: /rdap/nameservers?name=exam*.com
    metricInformationBuilder.setSearchType(SearchType.BY_NAMESERVER_NAME);
    results =
        searchByName(
            recordWildcardType(
                RdapSearchPattern.createFromLdhOrUnicodeDomainName(nameParam.get())));
  } else {
    // RDAP Technical Implementation Guide 2.2.3 - we MUST support nameserver search queries based
    // on IP address as defined in RFC7482 3.2.2. Doesn't require pattern matching
    //
    // syntax: /rdap/nameservers?ip=1.2.3.4
    metricInformationBuilder.setSearchType(SearchType.BY_NAMESERVER_ADDRESS);
    InetAddress inetAddress;
    try {
      inetAddress = InetAddresses.forString(ipParam.get());
    } catch (IllegalArgumentException e) {
      throw new BadRequestException("Invalid value of ip parameter");
    }
    results = searchByIp(inetAddress);
  }
  if (results.nameserverSearchResults().isEmpty()) {
    throw new NotFoundException("No nameservers found");
  }
  return results;
}
 
Example 9
Source File: NetworkSetTest.java    From dhcp4j with Apache License 2.0 5 votes vote down vote up
private static void addRange(@Nonnull NetworkSet set, @Nonnull String a, @Nonnull String b) {
    InetAddressRange range = new InetAddressRange(
            InetAddresses.forString(a),
            InetAddresses.forString(b));
    LOG.info("Add (inclusive) " + range);
    set.addRange(range);
}
 
Example 10
Source File: InetAddressAdapter.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
public InetAddress unmarshal(AddressShim shim) throws IpVersionMismatchException {
  InetAddress inetAddress = InetAddresses.forString(shim.ipAddress);
  // Enforce that "v6" is used iff the address is ipv6. (For ipv4, "v4" is allowed to be missing.)
  if (inetAddress instanceof Inet6Address != "v6".equals(shim.ipVersion)) {
    throw new IpVersionMismatchException();
  }
  return inetAddress;
}
 
Example 11
Source File: LocalAppEngineServerLaunchConfigurationDelegate.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve a host or IP address to an IP address.
 *
 * @return an {@link InetAddress}, or {@code null} if unable to be resolved (equivalent to
 *         {@code INADDR_ANY})
 */
static InetAddress resolveAddress(String ipOrHost) {
  if (!Strings.isNullOrEmpty(ipOrHost)) {
    if (InetAddresses.isInetAddress(ipOrHost)) {
      return InetAddresses.forString(ipOrHost);
    }
    try {
      InetAddress[] addresses = InetAddress.getAllByName(ipOrHost);
      return addresses[0];
    } catch (UnknownHostException ex) {
      logger.info("Unable to resolve '" + ipOrHost + "' to an address"); //$NON-NLS-1$ //$NON-NLS-2$
    }
  }
  return null;
}
 
Example 12
Source File: PCCMockCommon.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
static TestingSessionListener checkSessionListenerNotNull(final TestingSessionListenerFactory factory,
        final String localAddress) {
    final Stopwatch sw = Stopwatch.createStarted();
    TestingSessionListener listener;
    final InetAddress address = InetAddresses.forString(localAddress);
    while (sw.elapsed(TimeUnit.SECONDS) <= 60) {
        listener = factory.getSessionListenerByRemoteAddress(address);
        if (listener == null) {
            Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
        } else {
            return listener;
        }
    }
    throw new NullPointerException();
}
 
Example 13
Source File: PeerAddress.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public static PeerAddress localhost(NetworkParameters params) {
    return new PeerAddress(params, InetAddresses.forString("127.0.0.1"), params.getPort());
}
 
Example 14
Source File: RouterId.java    From bgpcep with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RouterId load(final String key) {
    final InetAddress addr = InetAddresses.forString(key);
    checkArgument(addr instanceof Inet4Address, "Invalid address %s", key);
    return BY_PEER_ID.getUnchecked(new PeerId(RouterId.PEER_ID_PREFIX.concat(key)));
}
 
Example 15
Source File: InetAddressSetConverter.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Override
InetAddress fromString(String value) {
  return InetAddresses.forString(value);
}
 
Example 16
Source File: BgpSessionManagerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    peer1 = new TestBgpPeer(BGP_PEER1_ID);
    peer2 = new TestBgpPeer(BGP_PEER2_ID);
    peer3 = new TestBgpPeer(BGP_PEER3_ID);
    peers.clear();
    peers.add(peer1);
    peers.add(peer2);
    peers.add(peer3);

    //
    // Setup the BGP Session Manager to test, and start listening for BGP
    // connections.
    //
    bgpSessionManager = new BgpSessionManager();

    routeService = createNiceMock(RouteAdminService.class);
    replay(routeService);
    bgpSessionManager.routeService = routeService;

    ClusterService clusterService = createMock(ClusterService.class);
    expect(clusterService.getLocalNode())
            .andReturn(new DefaultControllerNode(NODE_ID, LOCAL)).anyTimes();
    replay(clusterService);
    bgpSessionManager.clusterService = clusterService;

    // NOTE: We use port 0 to bind on any available port
    ComponentContext componentContext = createMock(ComponentContext.class);
    getDictionaryMock(componentContext);
    replay(componentContext);
    bgpSessionManager.activate(componentContext);

    // Get the port number the BGP Session Manager is listening on
    Channel serverChannel = TestUtils.getField(bgpSessionManager,
                                               "serverChannel");
    SocketAddress socketAddress = serverChannel.getLocalAddress();
    InetSocketAddress inetSocketAddress =
        (InetSocketAddress) socketAddress;
    InetAddress connectToAddress = InetAddresses.forString("127.0.0.1");
    connectToSocket = new InetSocketAddress(connectToAddress,
                                            inetSocketAddress.getPort());

    //
    // Setup the AS Paths
    //
    ArrayList<BgpRouteEntry.PathSegment> pathSegments = new ArrayList<>();
    byte pathSegmentType1 = (byte) BgpConstants.Update.AsPath.AS_SEQUENCE;
    ArrayList<Long> segmentAsNumbers1 = new ArrayList<>();
    segmentAsNumbers1.add(65010L);
    segmentAsNumbers1.add(65020L);
    segmentAsNumbers1.add(65030L);
    BgpRouteEntry.PathSegment pathSegment1 =
        new BgpRouteEntry.PathSegment(pathSegmentType1, segmentAsNumbers1);
    pathSegments.add(pathSegment1);
    asPathShort = new BgpRouteEntry.AsPath(new ArrayList<>(pathSegments));
    //
    byte pathSegmentType2 = (byte) BgpConstants.Update.AsPath.AS_SET;
    ArrayList<Long> segmentAsNumbers2 = new ArrayList<>();
    segmentAsNumbers2.add(65041L);
    segmentAsNumbers2.add(65042L);
    segmentAsNumbers2.add(65043L);
    BgpRouteEntry.PathSegment pathSegment2 =
        new BgpRouteEntry.PathSegment(pathSegmentType2, segmentAsNumbers2);
    pathSegments.add(pathSegment2);
    //
    asPathLong = new BgpRouteEntry.AsPath(pathSegments);
}
 
Example 17
Source File: PeerAddress.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public static PeerAddress localhost(NetworkParameters params) {
    return new PeerAddress(params, InetAddresses.forString("127.0.0.1"), params.getPort());
}
 
Example 18
Source File: AddNodeRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public AddNodeRequest(String nodeIp, int nodePort) {
    this.nodeIp = nodeIp;
    this.nodePort = nodePort;
    this.address = InetAddresses.forString(nodeIp);
}
 
Example 19
Source File: DataTransferSaslUtil.java    From big-c with Apache License 2.0 3 votes vote down vote up
/**
 * Returns InetAddress from peer.  The getRemoteAddressString has the form
 * [host][/ip-address]:port.  The host may be missing.  The IP address (and
 * preceding '/') may be missing.  The port preceded by ':' is always present.
 *
 * @param peer
 * @return InetAddress from peer
 */
public static InetAddress getPeerAddress(Peer peer) {
  String remoteAddr = peer.getRemoteAddressString().split(":")[0];
  int slashIdx = remoteAddr.indexOf('/');
  return InetAddresses.forString(slashIdx != -1 ?
      remoteAddr.substring(slashIdx + 1, remoteAddr.length()) :
      remoteAddr);
}
 
Example 20
Source File: DataTransferSaslUtil.java    From hadoop with Apache License 2.0 3 votes vote down vote up
/**
 * Returns InetAddress from peer.  The getRemoteAddressString has the form
 * [host][/ip-address]:port.  The host may be missing.  The IP address (and
 * preceding '/') may be missing.  The port preceded by ':' is always present.
 *
 * @param peer
 * @return InetAddress from peer
 */
public static InetAddress getPeerAddress(Peer peer) {
  String remoteAddr = peer.getRemoteAddressString().split(":")[0];
  int slashIdx = remoteAddr.indexOf('/');
  return InetAddresses.forString(slashIdx != -1 ?
      remoteAddr.substring(slashIdx + 1, remoteAddr.length()) :
      remoteAddr);
}