java.net.InetAddress#getLoopbackAddress ( )源码实例Demo

下面列出了java.net.InetAddress#getLoopbackAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: flink   文件: ExecutionVertexLocalityTest.java
/**
 * This test validates that vertices with too many input streams do not have a location
 * preference any more.
 */
@Test
public void testNoLocalityInputLargeAllToAll() throws Exception {
	final int parallelism = 100;

	final ExecutionGraph graph = createTestGraph(parallelism, true);

	// set the location for all sources to a distinct location
	for (int i = 0; i < parallelism; i++) {
		ExecutionVertex source = graph.getAllVertices().get(sourceVertexId).getTaskVertices()[i];
		TaskManagerLocation location = new TaskManagerLocation(
				ResourceID.generate(), InetAddress.getLoopbackAddress(), 10000 + i);
		initializeLocation(source, location);
	}

	// validate that the target vertices have no location preference
	for (int i = 0; i < parallelism; i++) {
		ExecutionVertex target = graph.getAllVertices().get(targetVertexId).getTaskVertices()[i];

		Iterator<CompletableFuture<TaskManagerLocation>> preference = target.getPreferredLocations().iterator();
		assertFalse(preference.hasNext());
	}
}
 
源代码2 项目: openjdk-jdk8u   文件: SctpNet.java
private static SocketAddress getRevealedLocalAddress(SocketAddress sa,
                                                     SecurityManager sm)
{
    if (sm == null || sa == null)
        return sa;
    InetSocketAddress ia = (InetSocketAddress)sa;
    try{
        sm.checkConnect(ia.getAddress().getHostAddress(), -1);
        // Security check passed
    } catch (SecurityException e) {
        // Return loopback address
        return new InetSocketAddress(InetAddress.getLoopbackAddress(),
                                     ia.getPort());
    }
    return sa;
}
 
源代码3 项目: jdk8u-jdk   文件: SctpNet.java
private static SocketAddress getRevealedLocalAddress(SocketAddress sa,
                                                     SecurityManager sm)
{
    if (sm == null || sa == null)
        return sa;
    InetSocketAddress ia = (InetSocketAddress)sa;
    try{
        sm.checkConnect(ia.getAddress().getHostAddress(), -1);
        // Security check passed
    } catch (SecurityException e) {
        // Return loopback address
        return new InetSocketAddress(InetAddress.getLoopbackAddress(),
                                     ia.getPort());
    }
    return sa;
}
 
源代码4 项目: flink   文件: SimpleSlotProvider.java
public SimpleSlotProvider(JobID jobId, int numSlots, TaskManagerGateway taskManagerGateway) {
	checkNotNull(jobId, "jobId");
	checkArgument(numSlots >= 0, "numSlots must be >= 0");

	this.slots = new ArrayDeque<>(numSlots);

	for (int i = 0; i < numSlots; i++) {
		SimpleSlotContext as = new SimpleSlotContext(
			new AllocationID(),
			new TaskManagerLocation(ResourceID.generate(), InetAddress.getLoopbackAddress(), 10000 + i),
			0,
			taskManagerGateway,
			ResourceProfile.UNKNOWN);
		slots.add(as);
	}

	allocatedSlots = new HashMap<>(slots.size());
}
 
源代码5 项目: streamsx.topology   文件: TCPTestServer.java
/**
 * Initialize the MINA server.
 */
public TCPTestServer(int port, boolean loopback, IoHandler handler) throws Exception {

    acceptor = new NioSocketAcceptor();

    IoFilter tupleEncoder = new ProtocolCodecFilter(new TestTupleEncoder(),
            new TestTupleDecoder());

    acceptor.getFilterChain().addLast("testtuples", tupleEncoder);

    acceptor.setHandler(handler);

    // Get the bind address now so the majority of
    // errors are caught at initialization time.
    bindAddress = new InetSocketAddress(
            loopback ? InetAddress.getLoopbackAddress() : InetAddress.getLocalHost(), port);
}
 
源代码6 项目: ant-ivy   文件: IvyAuthenticatorTest.java
/**
 * Tests that when {@link IvyAuthenticator} can't handle a authentication request and falls back
 * on an authenticator that was previously set, before IvyAuthenticator installed on top of it,
 * the other authenticator gets passed all the relevant requesting information, including the
 * {@link Authenticator#getRequestingURL() requesting URL} and
 * {@link Authenticator#getRequestorType() request type}
 *
 * @throws Exception if something goes wrong
 * @see <a href="https://issues.apache.org/jira/browse/IVY-1557">IVY-1557</a>
 */
@Test
public void testRequestURLAndType() throws Exception {
    testAuthenticator.expectedHost = "localhost";
    testAuthenticator.expectedPort = 12345;
    testAuthenticator.expectedPrompt = "Test prompt - testRequestURLAndType";
    testAuthenticator.expectedProtocol = "HTTP/1.1";
    testAuthenticator.expectedURL = new URL("http", "localhost", 12345, "/a/b/c");
    testAuthenticator.expectedType = Authenticator.RequestorType.PROXY;
    testAuthenticator.expectedScheme = "BASIC";
    testAuthenticator.expectedSite = InetAddress.getLoopbackAddress();

    // trigger the authentication
    final PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(testAuthenticator.expectedHost, testAuthenticator.expectedSite,
            testAuthenticator.expectedPort, testAuthenticator.expectedProtocol, testAuthenticator.expectedPrompt,
            testAuthenticator.expectedScheme, testAuthenticator.expectedURL, testAuthenticator.expectedType);

    assertNotNull("Expected a password authentication, but got none", auth);
    assertEquals("Unexpected username", "dummy", auth.getUserName());
    assertTrue("Unexpected password", Arrays.equals("dummy".toCharArray(), auth.getPassword()));
}
 
源代码7 项目: bcm-android   文件: TestWithNetworkConnections.java
protected void startPeerServer(int i) throws IOException {
    peerServers[i] = new NioServer(new StreamConnectionFactory() {
        @Nullable
        @Override
        public StreamConnection getNewConnection(InetAddress inetAddress, int port) {
            return new InboundMessageQueuer(UNITTEST) {
                @Override
                public void connectionClosed() {
                }

                @Override
                public void connectionOpened() {
                    newPeerWriteTargetQueue.offer(this);
                }
            };
        }
    }, new InetSocketAddress(InetAddress.getLoopbackAddress(), 2000 + i));
    peerServers[i].startAsync();
    peerServers[i].awaitRunning();
}
 
源代码8 项目: openjdk-jdk8u   文件: Utils.java
/**
 * Returns the socket address of an endpoint that refuses connections. The
 * endpoint is an InetSocketAddress where the address is the loopback address
 * and the port is a system port (1-1023 range).
 * This method is a better choice than getFreePort for tests that need
 * an endpoint that refuses connections.
 */
public static InetSocketAddress refusingEndpoint() {
    InetAddress lb = InetAddress.getLoopbackAddress();
    int port = 1;
    while (port < 1024) {
        InetSocketAddress sa = new InetSocketAddress(lb, port);
        try {
            SocketChannel.open(sa).close();
        } catch (IOException ioe) {
            return sa;
        }
        port++;
    }
    throw new RuntimeException("Unable to find system port that is refusing connections");
}
 
@VisibleForTesting
void checkPorts(RunConfiguration devServerRunConfiguration,
    BiPredicate<InetAddress, Integer> portInUse) throws CoreException {
  InetAddress serverHost = InetAddress.getLoopbackAddress();
  if (devServerRunConfiguration.getHost() != null) {
    serverHost = LocalAppEngineServerLaunchConfigurationDelegate
        .resolveAddress(devServerRunConfiguration.getHost());
  }
  serverPort = checkPort(serverHost,
      ifNull(devServerRunConfiguration.getPort(), DEFAULT_SERVER_PORT), portInUse);
}
 
@UsesJava7  // fallback to InetAddress.getLoopbackAddress()
private InetAddress getLocalHost() {
	try {
		return InetAddress.getLocalHost();
	}
	catch (UnknownHostException ex) {
		return InetAddress.getLoopbackAddress();
	}
}
 
源代码11 项目: halo   文件: InetAddressTest.java
@Test
public void getMachaineAddressTest() throws UnknownHostException {
    InetAddress localHost = InetAddress.getLocalHost();
    log.debug("Localhost: " + localHost.getHostAddress());

    InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
    log.debug("Loopback: " + loopbackAddress.getHostAddress());
}
 
源代码12 项目: twill   文件: InMemoryZKServer.java
private InetSocketAddress getAddress(int port) {
  int socketPort = port < 0 ? 0 : port;
  if (Boolean.parseBoolean(System.getProperties().getProperty("twill.zk.server.localhost", "true"))) {
    return new InetSocketAddress(InetAddress.getLoopbackAddress(), socketPort);
  } else {
    return new InetSocketAddress(socketPort);
  }
}
 
源代码13 项目: dragonwell8_jdk   文件: getOriginalHostName.java
public static void main(String[] args) throws Exception {
    final String HOST = "dummyserver.java.net";
    InetAddress ia = null;
    ia = InetAddress.getByName(HOST);
    testInetAddress(ia, HOST);
    ia = InetAddress.getByName("255.255.255.0");
    testInetAddress(ia, null);
    ia = InetAddress.getByAddress(new byte[]{1,1,1,1});
    testInetAddress(ia, null);
    ia = InetAddress.getLocalHost();
    testInetAddress(ia, ia.getHostName());
    ia = InetAddress.getLoopbackAddress();
    testInetAddress(ia, ia.getHostName());
}
 
源代码14 项目: flink   文件: NettyClientServerSslTest.java
private static NettyConfig createNettyConfig(Configuration config) {
	return new NettyConfig(
			InetAddress.getLoopbackAddress(),
			NetUtils.getAvailablePort(),
			NettyTestUtil.DEFAULT_SEGMENT_SIZE,
			1,
			config);
}
 
源代码15 项目: openjdk-jdk9   文件: JdiDefaultExecutionControl.java
/**
 * Creates an ExecutionControl instance based on a JDI
 * {@code ListeningConnector} or {@code LaunchingConnector}.
 *
 * Initialize JDI and use it to launch the remote JVM. Set-up a socket for
 * commands and results. This socket also transports the user
 * input/output/error.
 *
 * @param env the context passed by
 * {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
 * @param remoteAgent the remote agent to launch
 * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
 * otherwise we start explicitly and use ListeningConnector
 * @param host explicit hostname to use, if null use discovered
 * hostname, applies to listening only (!isLaunch)
 * @return the channel
 * @throws IOException if there are errors in set-up
 */
static ExecutionControl create(ExecutionEnv env, String remoteAgent,
        boolean isLaunch, String host, int timeout) throws IOException {
    try (final ServerSocket listener = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
        // timeout on I/O-socket
        listener.setSoTimeout(timeout);
        int port = listener.getLocalPort();

        // Set-up the JDI connection
        JdiInitiator jdii = new JdiInitiator(port,
                env.extraRemoteVMOptions(), remoteAgent, isLaunch, host,
                timeout, Collections.emptyMap());
        VirtualMachine vm = jdii.vm();
        Process process = jdii.process();

        List<Consumer<String>> deathListeners = new ArrayList<>();
        Util.detectJdiExitEvent(vm, s -> {
            for (Consumer<String> h : deathListeners) {
                h.accept(s);
            }
        });

        // Set-up the commands/reslts on the socket.  Piggy-back snippet
        // output.
        Socket socket = listener.accept();
        // out before in -- match remote creation so we don't hang
        OutputStream out = socket.getOutputStream();
        Map<String, OutputStream> outputs = new HashMap<>();
        outputs.put("out", env.userOut());
        outputs.put("err", env.userErr());
        Map<String, InputStream> input = new HashMap<>();
        input.put("in", env.userIn());
        return remoteInputOutput(socket.getInputStream(), out, outputs, input,
                (objIn, objOut) -> new JdiDefaultExecutionControl(env,
                                    objOut, objIn, vm, process, remoteAgent, deathListeners));
    }
}
 
@Test
public void shouldFailCreatingSocketForUnknownHost() throws Exception {
    // Given
    String unknownHost = "localhorst";
    InetAddress localAddress = InetAddress.getLoopbackAddress();
    int localPort = 28080;
    HttpConnectionParams params = new HttpConnectionParams();
    params.setConnectionTimeout(60000);
    // When / Then
    assertThrows(
            IOException.class,
            () ->
                    socketFactory.createSocket(
                            unknownHost, serverPort, localAddress, localPort, params));
}
 
源代码17 项目: jdk8u-dev-jdk   文件: ThrowingNameService.java
@Override
public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException {
    if (firstCall) {
        firstCall = false;
        // throw unchecked exception first time round
        throw new IllegalStateException();
    }

    // return any valid address
    return new InetAddress[] { InetAddress.getLoopbackAddress() };
}
 
源代码18 项目: openjdk-jdk8u   文件: DisconnectNPETest.java
private void initRes() throws IOException {
    serverSocket = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
    server = new TestLDAPServer();
    server.start();
}
 
源代码19 项目: flink   文件: LocalTaskManagerLocation.java
public LocalTaskManagerLocation() {
	super(ResourceID.generate(), InetAddress.getLoopbackAddress(), 42);
}
 
源代码20 项目: bt   文件: PeerExchange_IT.java
@Override
public InetAddress getAcceptorAddress() {
    return InetAddress.getLoopbackAddress();
}