java.net.InetAddress Java Examples

The following examples show how to use java.net.InetAddress. 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: AbstractMiddleTierService.java    From ReactiveLab with Apache License 2.0 7 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 #2
Source File: ExtendedConnectionOperator.java    From lavaplayer with 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 #3
Source File: IPAddressName.java    From hottub with 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 #4
Source File: libcTest.java    From JavaLinuxNet with 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 #5
Source File: InitialToken.java    From openjdk-jdk9 with 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 #6
Source File: NetworkUtils.java    From kylin with 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 #7
Source File: Inet6AddressSerializationTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: SdpProvider.java    From jdk8u-jdk with 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 #10
Source File: HashSpread.java    From openjdk-jdk9 with 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 File: LsRequest.java    From onos with 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 File: NacosAutoServiceRegistrationIpNetworkInterfaceTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: BaseCassandraModule.java    From arcusplatform with 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 #14
Source File: AbstractServerBase.java    From Flink-CEPplus with 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 #15
Source File: InternalMetadataFactory.java    From cassandra-exporter with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: BindingMulticastAddressHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
void handleRuntimeChange(OperationContext context, ModelNode operation, String attributeName, ModelNode attributeValue, SocketBinding binding) throws OperationFailedException {
    final InetAddress address;
    if(attributeValue.isDefined()) {
        String addrString = attributeValue.asString();
        try {
            address = InetAddress.getByName(addrString);
        } catch (UnknownHostException e) {
            throw ServerLogger.ROOT_LOGGER.failedToResolveMulticastAddress(e, addrString);
        }
    } else {
        address = null;
    }
    binding.setMulticastAddress(address);
}
 
Example #17
Source File: StoreApp.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
private static void logApplicationStartup(Environment env) {
    String protocol = "http";
    if (env.getProperty("server.ssl.key-store") != null) {
        protocol = "https";
    }
    String serverPort = env.getProperty("server.port");
    String contextPath = env.getProperty("server.servlet.context-path");
    if (StringUtils.isBlank(contextPath)) {
        contextPath = "/";
    }
    String hostAddress = "localhost";
    try {
        hostAddress = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        log.warn("The host name could not be determined, using `localhost` as fallback");
    }
    log.info("\n----------------------------------------------------------\n\t" +
            "Application '{}' is running! Access URLs:\n\t" +
            "Local: \t\t{}://localhost:{}{}\n\t" +
            "External: \t{}://{}:{}{}\n\t" +
            "Profile(s): \t{}\n----------------------------------------------------------",
        env.getProperty("spring.application.name"),
        protocol,
        serverPort,
        contextPath,
        protocol,
        hostAddress,
        serverPort,
        contextPath,
        env.getActiveProfiles());

    String configServerStatus = env.getProperty("configserver.status");
    if (configServerStatus == null) {
        configServerStatus = "Not found or not setup for this application";
    }
    log.info("\n----------------------------------------------------------\n\t" +
            "Config Server: \t{}\n----------------------------------------------------------", configServerStatus);
}
 
Example #18
Source File: SimpleNode.java    From jdk8u_jdk with 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 #19
Source File: SaneSessionTest.java    From jfreesane with 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 #20
Source File: MySQLDatabaseServer.java    From netbeans with 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 #21
Source File: CasquatchPodamFactoryImpl.java    From casquatch with 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 #22
Source File: Util.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
public static String data2string(Object data) {
   if(data == null)
     return "<null>";
   else if(data instanceof InetAddress)
     return ((InetAddress)data).getHostName();
   else if(data instanceof InetAddress[]) {
     InetAddress[] tmp = (InetAddress[])data;
     String result = "";
     for(int i = 0; i < tmp.length; i++)
result += "[" + i + "]" + data2string(tmp[i]);
     return result;
   }
   else return data.toString();
 }
 
Example #23
Source File: Socks5DatagramSocket.java    From T0rlib4Android with 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 #24
Source File: AttachmentServer.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
public AttachmentServer(Context context, Attachment attachment)
    throws IOException
{
  try {
    this.context      = context;
    this.attachment   = attachment;
    this.socket       = new ServerSocket(0, 0, InetAddress.getByAddress(new byte[]{127, 0, 0, 1}));
    this.port         = socket.getLocalPort();
    this.auth         = Hex.toStringCondensed(Util.getSecretBytes(16));

    this.socket.setSoTimeout(5000);
  } catch (UnknownHostException e) {
    throw new AssertionError(e);
  }
}
 
Example #25
Source File: MachineInfo.java    From disconf with 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 #26
Source File: DNSJavaNameService.java    From Virtual-Hosts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Performs a reverse DNS lookup.
 * @param addr The ip address to lookup.
 * @return The host name found for the ip address.
 */
public String
getHostByAddr(byte [] addr) throws UnknownHostException {
	Name name = ReverseMap.fromAddress(InetAddress.getByAddress(addr));
	Record [] records = new Lookup(name, Type.PTR).run();
	if (records == null)
		throw new UnknownHostException();
	return ((PTRRecord) records[0]).getTarget().toString();
}
 
Example #27
Source File: CamelSinkHTTPITCase.java    From camel-kafka-connector with 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 #28
Source File: CommonUtil.java    From AndroidWebServ with 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 #29
Source File: SocksProxySocketFactory.java    From localization_nifi with 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 #30
Source File: HostAddress.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
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);
}