Java Code Examples for java.net.InetAddress

The following examples show how to use java.net.InetAddress. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public Optional<EndpointMetadata> endpointMetadata(final InetAddress endpoint) {
    final IEndpointSnitch endpointSnitch = DatabaseDescriptor.getEndpointSnitch();

    return Optional.of(new EndpointMetadata() {
        @Override
        public String dataCenter() {
            return endpointSnitch.getDatacenter(endpoint);
        }

        @Override
        public String rack() {
            return endpointSnitch.getRack(endpoint);
        }
    });
}
 
Example 2
Source Project: Flink-CEPplus   Source File: AbstractServerBase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates the {@link AbstractServerBase}.
 *
 * <p>The server needs to be started via {@link #start()}.
 *
 * @param serverName the name of the server
 * @param bindAddress address to bind to
 * @param bindPortIterator port to bind to
 * @param numEventLoopThreads number of event loop threads
 */
protected AbstractServerBase(
		final String serverName,
		final InetAddress bindAddress,
		final Iterator<Integer> bindPortIterator,
		final Integer numEventLoopThreads,
		final Integer numQueryThreads) {

	Preconditions.checkNotNull(bindPortIterator);
	Preconditions.checkArgument(numEventLoopThreads >= 1, "Non-positive number of event loop threads.");
	Preconditions.checkArgument(numQueryThreads >= 1, "Non-positive number of query threads.");

	this.serverName = Preconditions.checkNotNull(serverName);
	this.bindAddress = Preconditions.checkNotNull(bindAddress);
	this.numEventLoopThreads = numEventLoopThreads;
	this.numQueryThreads = numQueryThreads;

	this.bindPortRange = new HashSet<>();
	while (bindPortIterator.hasNext()) {
		int port = bindPortIterator.next();
		Preconditions.checkArgument(port >= 0 && port <= 65535,
				"Invalid port configuration. Port must be between 0 and 65535, but was " + port + ".");
		bindPortRange.add(port);
	}
}
 
Example 3
Source Project: arcusplatform   Source File: BaseCassandraModule.java    License: Apache License 2.0 6 votes vote down vote up
private static List<InetAddress> parseContactPoints(String commaDelimitedList) {
    List<InetAddress> contactPoints = new ArrayList<>();

    String[] cps = commaDelimitedList.split(",");
    for (int i = 0; i < cps.length; i++) {
        try {
            InetAddress[] addrs = InetAddress.getAllByName(cps[i].trim());
            LOGGER.debug("{} resolves to: {}", cps[i], addrs);

            for (InetAddress addr : addrs) {
                contactPoints.add(addr);
            }
        } catch (UnknownHostException ex) {
            // ignore so we can use any working addresses
            // that are available.
        }
    }

    if (contactPoints.isEmpty()) {
        throw new RuntimeException("Unable to configure Cassandra cluster, the hosts specified in cassandra.contactPoints could not be resolved");
    }

    return contactPoints;
}
 
Example 4
Source Project: ReactiveLab   Source File: AbstractMiddleTierService.java    License: Apache License 2.0 6 votes vote down vote up
protected InstanceInfo createInstanceInfo(int port) {
    final HashSet<ServicePort> ports = new HashSet<>(Arrays.asList(new ServicePort(port, false)));

    String hostAddress = "unknown";
    try {
        hostAddress = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        hostAddress = "unknown-" + UUID.randomUUID();
    }

    return new InstanceInfo.Builder()
            .withId(hostAddress + "-" + port)
            .withApp("reactive-lab")
            .withStatus(InstanceInfo.Status.UP)
            .withVipAddress(eurekaVipAddress)
            .withPorts(ports)
            .withDataCenterInfo(BasicDataCenterInfo.fromSystemData())
            .build();
}
 
Example 5
Source Project: JavaLinuxNet   Source File: libcTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testin_addr() throws Exception {
    libc.in_addr a;
    a=new libc.in_addr();
    Assert.assertEquals(0, a.address);

    a=new libc.in_addr(0x01020304);
    Assert.assertEquals(0x01020304, a.address);
    InetAddress ax=a.toInetAddress();
    Assert.assertNotNull(ax);
    Assert.assertEquals("/1.2.3.4", ax.toString());
    Assert.assertEquals("0x01020304",a.toString());

    a=new libc.in_addr(0xfffffffe);
    Assert.assertEquals(0xfffffffe, a.address);
    ax=a.toInetAddress();
    Assert.assertNotNull(ax);
    Assert.assertEquals("/255.255.255.254", ax.toString());
    Assert.assertEquals("0xfffffffe",a.toString());

}
 
Example 6
Source Project: hottub   Source File: IPAddressName.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse an IPv4 address.
 *
 * @param name IPv4 address with optional mask values
 * @throws IOException on error
 */
private void parseIPv4(String name) throws IOException {

    // Parse name into byte-value address components
    int slashNdx = name.indexOf('/');
    if (slashNdx == -1) {
        address = InetAddress.getByName(name).getAddress();
    } else {
        address = new byte[8];

        // parse mask
        byte[] mask = InetAddress.getByName
            (name.substring(slashNdx+1)).getAddress();

        // parse base address
        byte[] host = InetAddress.getByName
            (name.substring(0, slashNdx)).getAddress();

        System.arraycopy(host, 0, address, 0, 4);
        System.arraycopy(mask, 0, address, 4, 4);
    }
}
 
Example 7
Source Project: kylin   Source File: NetworkUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String getLocalIp() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                continue;
            if (iface.getName().startsWith("vboxnet"))
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                final String ip = addr.getHostAddress();
                if (Inet4Address.class == addr.getClass())
                    return ip;
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 8
Source Project: jdk8u-jdk   Source File: SdpProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void convertTcpToSdpIfMatch(FileDescriptor fdObj,
                                           Action action,
                                           InetAddress address,
                                           int port)
    throws IOException
{
    boolean matched = false;
    for (Rule rule: rules) {
        if (rule.match(action, address, port)) {
            SdpSupport.convertSocket(fdObj);
            matched = true;
            break;
        }
    }
    if (log != null) {
        String addr = (address instanceof Inet4Address) ?
            address.getHostAddress() : "[" + address.getHostAddress() + "]";
        if (matched) {
            log.format("%s to %s:%d (socket converted to SDP protocol)\n", action, addr, port);
        } else {
            log.format("%s to %s:%d (no match)\n", action, addr, port);
        }
    }
}
 
Example 9
private static ServiceRequestContext newServiceContext(
        String path, @Nullable String query) throws Exception {

    final InetSocketAddress remoteAddress = new InetSocketAddress(
            InetAddress.getByAddress("client.com", new byte[] { 1, 2, 3, 4 }), 5678);
    final InetSocketAddress localAddress = new InetSocketAddress(
            InetAddress.getByAddress("server.com", new byte[] { 5, 6, 7, 8 }), 8080);

    final String pathAndQuery = path + (query != null ? '?' + query : "");
    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.GET, pathAndQuery,
                                                             HttpHeaderNames.AUTHORITY, "server.com:8080",
                                                             HttpHeaderNames.USER_AGENT, "some-client"));

    final ServiceRequestContext ctx =
            ServiceRequestContext.builder(req)
                                 .sslSession(newSslSession())
                                 .remoteAddress(remoteAddress)
                                 .localAddress(localAddress)
                                 .proxiedAddresses(
                                         ProxiedAddresses.of(new InetSocketAddress("9.10.11.12", 0)))
                                 .build();

    ctx.setAttr(MY_ATTR, new CustomObject("some-name", "some-value"));
    return ctx;
}
 
Example 10
Source Project: openjdk-jdk9   Source File: HashSpread.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generate and return a random IPv6 address.
 */
static InetAddress randomIPv6Adress() {
    StringBuffer sb = new StringBuffer();

    for (int i=0; i<8; i++) {

        if (i > 0)
            sb.append(":");

        for (int j=0; j<4; j++) {
            int v = r.nextInt(16);
            if (v < 10) {
                sb.append(Integer.toString(v));
            } else {
                char c = (char) ('A' + v - 10);
                sb.append(c);
            }
        }
    }

    try {
        return InetAddress.getByName(sb.toString());
    } catch (UnknownHostException x) {
        throw new Error("Internal error in test");
    }
}
 
Example 11
Source Project: onos   Source File: LsRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets LS request packet body as byte array.
 *
 * @return LS request packet body as byte array
 */
public byte[] getLsrBodyAsByteArray() {
    List<Byte> bodyLst = new ArrayList<>();

    try {
        for (LsRequestPacket lsrPacket : linkStateRequests) {
            bodyLst.addAll(Bytes.asList(OspfUtil.convertToFourBytes(lsrPacket.lsType())));
            bodyLst.addAll(Bytes.asList(InetAddress.getByName(lsrPacket.linkStateId()).getAddress()));
            bodyLst.addAll(Bytes.asList(InetAddress.getByName(lsrPacket.ownRouterId()).getAddress()));
        }
    } catch (Exception e) {
        log.debug("Error::getLsrBodyAsByteArray {}", e.getMessage());
        return Bytes.toArray(bodyLst);
    }

    return Bytes.toArray(bodyLst);
}
 
Example 12
Source Project: lavaplayer   Source File: ExtendedConnectionOperator.java    License: Apache License 2.0 6 votes vote down vote up
private InetAddress[] resolveAddresses(HttpHost host, HttpContext context) throws IOException {
  if (host.getAddress() != null) {
    return new InetAddress[] { host.getAddress() };
  }

  Object resolvedObject = context.getAttribute(RESOLVED_ADDRESSES);

  if (resolvedObject instanceof ResolvedAddresses) {
    ResolvedAddresses resolved = (ResolvedAddresses) resolvedObject;

    if (resolved.host.equals(host)) {
      return resolved.addresses;
    }
  }

  return dnsResolver.resolve(host.getHostName());
}
 
Example 13
Source Project: openjdk-jdk9   Source File: InitialToken.java    License: GNU General Public License v2.0 6 votes vote down vote up
private byte[] getAddrBytes(InetAddress addr) throws GSSException {
    int addressType = getAddrType(addr);
    byte[] addressBytes = addr.getAddress();
    if (addressBytes != null) {
        switch (addressType) {
            case CHANNEL_BINDING_AF_INET:
                if (addressBytes.length != Inet4_ADDRSZ) {
                    throw new GSSException(GSSException.FAILURE, -1,
                    "Incorrect AF-INET address length in ChannelBinding.");
                }
                return (addressBytes);
            case CHANNEL_BINDING_AF_INET6:
                if (addressBytes.length != Inet6_ADDRSZ) {
                    throw new GSSException(GSSException.FAILURE, -1,
                    "Incorrect AF-INET6 address length in ChannelBinding.");
                }
                return (addressBytes);
            default:
                throw new GSSException(GSSException.FAILURE, -1,
                "Cannot handle non AF-INET addresses in ChannelBinding.");
        }
    }
    return null;
}
 
Example 14
static void testAllNetworkInterfaces() throws Exception {
    System.err.println("\n testAllNetworkInterfaces: \n ");
    for (Enumeration<NetworkInterface> e = NetworkInterface
            .getNetworkInterfaces(); e.hasMoreElements();) {
        NetworkInterface netIF = e.nextElement();
        for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
                .hasMoreElements();) {
            InetAddress iadr = iadrs.nextElement();
            if (iadr instanceof Inet6Address) {
                System.err.println("Test NetworkInterface:  " + netIF);
                Inet6Address i6adr = (Inet6Address) iadr;
                System.err.println("Testing with " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                testInet6AddressSerialization(i6adr, null);
            }
        }
    }
}
 
Example 15
private String getIPFromNetworkInterface(String networkInterface) {

		if (!TestConfig.hasValidNetworkInterface) {
			return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
		}

		try {
			NetworkInterface netInterface = NetworkInterface.getByName(networkInterface);

			Enumeration<InetAddress> inetAddress = netInterface.getInetAddresses();
			while (inetAddress.hasMoreElements()) {
				InetAddress currentAddress = inetAddress.nextElement();
				if (currentAddress instanceof Inet4Address
						&& !currentAddress.isLoopbackAddress()) {
					return currentAddress.getHostAddress();
				}
			}
			return networkInterface;
		}
		catch (Exception e) {
			return networkInterface;
		}
	}
 
Example 16
Source Project: mongodb-async-driver   Source File: MockMongoDBServer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new MockMongoDBServer.
 *
 * @throws IOException
 *             On a failure creating the server socket.
 */
public MockMongoDBServer() throws IOException {
    myRunningThreads = new CopyOnWriteArrayList<Thread>();
    myActiveClients = new CopyOnWriteArrayList<Socket>();

    myServerSocket = new ServerSocket();
    myServerSocket.bind(new InetSocketAddress(InetAddress
            .getByName("127.0.0.1"), 0));

    myRunning = false;
}
 
Example 17
Source Project: gemfirexd-oss   Source File: InternalLocator.java    License: Apache License 2.0 5 votes vote down vote up
public static LocatorStatusResponse statusLocator(int port, InetAddress bindAddress) throws IOException {
  //final int timeout = (60 * 2 * 1000); // 2 minutes
  final int timeout = Integer.MAX_VALUE; // 2 minutes

  try {
    return (LocatorStatusResponse) TcpClient.requestToServer(bindAddress, port,
        new LocatorStatusRequest(), timeout, true);
  }
  catch (ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 
Example 18
Source Project: Pix-Art-Messenger   Source File: Resolver.java    License: GNU General Public License v3.0 5 votes vote down vote up
static Result createDefault(final DNSName hostname, final int port) {
    InetAddress ip = null;
    try {
        ip = InetAddress.getByName(hostname.toString());
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return createDefault(hostname, ip, port);
}
 
Example 19
Source Project: Bytecoder   Source File: SSLSocketImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs an SSL connection to a server at a specified
 * address, and TCP port, using the authentication context
 * provided.
 *
 * This endpoint acts as the client, and may rejoin an existing SSL
 * session if appropriate.
 */
SSLSocketImpl(SSLContextImpl sslContext,
        InetAddress address, int peerPort) throws IOException {
    super();
    this.sslContext = sslContext;
    HandshakeHash handshakeHash = new HandshakeHash();
    this.conContext = new TransportContext(sslContext, this,
            new SSLSocketInputRecord(handshakeHash),
            new SSLSocketOutputRecord(handshakeHash), true);

    SocketAddress socketAddress = new InetSocketAddress(address, peerPort);
    connect(socketAddress, 0);
}
 
Example 20
public static void main(String[] args) throws Exception {
    if (InetAddress.getLocalHost().isLoopbackAddress()) {
        System.out.println("Test cannot run. getLocalHost returns a loopback address");
        return;
    }
    new SocksProxyVersion();
}
 
Example 21
Source Project: localization_nifi   Source File: SocksProxySocketFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress addr, int port, InetAddress localHostAddr, int localPort) throws IOException {
    Socket socket = createSocket();
    socket.bind(new InetSocketAddress(localHostAddr, localPort));
    socket.connect(new InetSocketAddress(addr, port));
    return socket;
}
 
Example 22
Source Project: AndroidWebServ   Source File: CommonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @brief 检查主机端口是否被占用
 * @param host 主机
 * @param port 端口
 * @return true: already in use, false: not.
 * @throws UnknownHostException 
 */
public boolean isPortInUse(String host, int port) throws UnknownHostException {
    boolean flag = false;
    InetAddress theAddress = InetAddress.getByName(host);
    try {
        Socket socket = new Socket(theAddress, port);
        socket.close();
        flag = true;
    } catch (IOException e) {
    }
    return flag;
}
 
Example 23
Source Project: camel-kafka-connector   Source File: CamelSinkHTTPITCase.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() throws IOException {
    validationHandler = new HTTPTestValidationHandler(10);
    byte[] ipAddr = new byte[]{127, 0, 0, 1};
    InetAddress localhost = InetAddress.getByAddress(ipAddr);
    localServer = ServerBootstrap.bootstrap()
            .setLocalAddress(localhost)
            .setListenerPort(HTTP_PORT)
            .registerHandler("/ckc", validationHandler)
            .create();

    localServer.start();
}
 
Example 24
Source Project: jdk8u_jdk   Source File: SimpleNode.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build the Inform entries from the syntactic tree.
 */
public void buildInformEntries(Hashtable<InetAddress, Vector<String>> dest) {
    if (children != null) {
        for (int i = 0; i < children.length; ++i) {
            SimpleNode n = (SimpleNode)children[i];
            if (n != null) {
                n.buildInformEntries(dest);
            }
        } /* end of loop */
    }
}
 
Example 25
Source Project: jfreesane   Source File: SaneSessionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void initSession() throws Exception {
  String address = System.getenv("SANE_TEST_SERVER_ADDRESS");
  if (address == null) {
    address = "localhost";
  }
  URI hostAndPort = URI.create("my://" + address);
  this.session =
      SaneSession.withRemoteSane(
          InetAddress.getByName(hostAndPort.getHost()),
          hostAndPort.getPort() == -1 ? 6566 : hostAndPort.getPort());
  session.setPasswordProvider(correctPasswordProvider);
}
 
Example 26
Source Project: casquatch   Source File: CasquatchPodamFactoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extends constructor for default settings
 */
public CasquatchPodamFactoryImpl() {
    super();
    this.getStrategy().addOrReplaceTypeManufacturer(BigDecimal.class, new BigDecimalStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(BigInteger.class, new BigIntegerStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(ByteBuffer.class, new ByteBufferStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(InetAddress.class, new InetAddressStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(Instant.class, new InstantStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(LocalDate.class, new LocalDateStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(LocalTime.class, new LocalTimeStrategy());
    this.getStrategy().addOrReplaceTypeManufacturer(UUID.class, new UUIDStrategy());
}
 
Example 27
Source Project: disconf   Source File: MachineInfo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return
 *
 * @Description: 获取机器名
 */
public static String getHostName() throws Exception {

    try {
        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();

        return hostname;

    } catch (UnknownHostException e) {

        throw new Exception(e);
    }
}
 
Example 28
Source Project: netbeans   Source File: MySQLDatabaseServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void checkConfiguration() throws DatabaseException {
    // Make sure the host name is a known host name
    try {
        InetAddress.getAllByName(getHost());
    } catch (UnknownHostException ex) {
        synchronized(this) {
            configError = NbBundle.getMessage(MySQLDatabaseServer.class, "MSG_UnknownHost", getHost());
            setState(ServerState.CONFIGERR);
        }
        LOGGER.log(Level.INFO, configError, ex);
        throw new DatabaseException(configError, ex);
    }

    try {
        String port = getPort();
        if (port == null) {
            throw new NumberFormatException();
        }
        Integer.valueOf(port);
    } catch (NumberFormatException nfe) {
        synchronized(this) {
            configError = NbBundle.getMessage(MySQLDatabaseServer.class, "MSG_InvalidPortNumber", getPort());
            setState(ServerState.CONFIGERR);
        }
        LOGGER.log(Level.INFO, configError, nfe);
        throw new DatabaseException(configError, nfe);
    }
}
 
Example 29
Source Project: T0rlib4Android   Source File: Socks5DatagramSocket.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Used by UDPRelayServer.
 */
Socks5DatagramSocket(boolean server_mode, UDPEncapsulation encapsulation,
		InetAddress relayIP, int relayPort) throws IOException {
	super();
	this.server_mode = server_mode;
	this.relayIP = relayIP;
	this.relayPort = relayPort;
	this.encapsulation = encapsulation;
	this.proxy = null;
}
 
Example 30
private int getAddrType(InetAddress inetAddress) {
    int addressType = 0;
    if (inetAddress instanceof Inet4Address)
        addressType = Krb5.ADDRTYPE_INET;
    else if (inetAddress instanceof Inet6Address)
        addressType = Krb5.ADDRTYPE_INET6;
    return (addressType);
}