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.
Example 1
Project: cassandra-exporter   File: InternalMetadataFactory.java    License: 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 2
Project: Flink-CEPplus   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
Project: arcusplatform   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
Project: ReactiveLab   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
Project: JavaLinuxNet   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
Project: hottub   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
Project: kylin   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
Project: jdk8u-jdk   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
Project: armeria   File: RequestContextExportingAppenderTest.java    License: 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 10
Project: openjdk-jdk9   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
Project: onos   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
Project: lavaplayer   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
Project: openjdk-jdk9   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
Project: hottub   File: Inet6AddressSerializationTest.java    License: 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 15
Project: spring-cloud-alibaba   File: NacosAutoServiceRegistrationIpNetworkInterfaceTests.java    License: 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 16
Project: mongodb-async-driver   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
Project: gemfirexd-oss   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
Project: Pix-Art-Messenger   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
Project: Bytecoder   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
Project: jdk8u-dev-jdk   File: SocksProxyVersion.java    License: GNU General Public License v2.0 5 votes vote down vote up
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
Project: localization_nifi   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
Project: AndroidWebServ   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
Project: camel-kafka-connector   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
Project: jdk8u_jdk   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
Project: jfreesane   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
Project: casquatch   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
Project: disconf   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
Project: netbeans   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
Project: T0rlib4Android   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
Project: openjdk-jdk8u-backup   File: HostAddress.java    License: 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);
}
 
Example 31
Project: deltachat-android   File: AttachmentServer.java    License: 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 32
Project: pdfxtk   File: Util.java    License: 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 33
Project: okta-jhipster-microservices-oauth-example   File: StoreApp.java    License: 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 34
Project: Virtual-Hosts   File: DNSJavaNameService.java    License: 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 35
Project: wildfly-core   File: BindingMulticastAddressHandler.java    License: 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 36
Project: dhcp4j   File: NetworkSetTest.java    License: 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 37
Project: hadoop   File: TestNetUtils.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyGetByName(String host, String ... searches) {
  InetAddress addr = null;
  try {
    addr = resolver.getByName(host);
  } catch (UnknownHostException e) {} // ignore
  assertNull(addr);
  assertBetterArrayEquals(searches, resolver.getHostSearches());
}
 
Example 38
Project: nifi   File: TestISPEnrichIP.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void successfulMaxMindResponseShouldFlowToFoundRelationshipWhenAsnIsNotSet() throws Exception {
    testRunner.setProperty(ISPEnrichIP.GEO_DATABASE_FILE, "./");
    testRunner.setProperty(ISPEnrichIP.IP_ADDRESS_ATTRIBUTE, "ip");

    final IspResponse ispResponse = getIspResponseWithoutASNDetail("1.2.3.4");

    when(databaseReader.isp(InetAddress.getByName("1.2.3.4"))).thenReturn(ispResponse);


    final Map<String, String> attributes = new HashMap<>();
    attributes.put("ip", "1.2.3.4");

    testRunner.enqueue(new byte[0], attributes);

    testRunner.run();

    List<MockFlowFile> notFound = testRunner.getFlowFilesForRelationship(ISPEnrichIP.REL_NOT_FOUND);
    List<MockFlowFile> found = testRunner.getFlowFilesForRelationship(ISPEnrichIP.REL_FOUND);

    assertEquals(0, notFound.size());
    assertEquals(1, found.size());

    FlowFile finishedFound = found.get(0);
    assertNotNull(finishedFound.getAttribute("ip.isp.lookup.micros"));
    assertNotNull(finishedFound.getAttribute("ip.isp.lookup.micros"));
    assertEquals("Apache NiFi - Test ISP", finishedFound.getAttribute("ip.isp.name"));
    assertEquals("Apache NiFi - Test Organization", finishedFound.getAttribute("ip.isp.organization"));
    assertNull(finishedFound.getAttribute("ip.isp.asn"));
    assertNull(finishedFound.getAttribute("ip.isp.asn.organization"));
}
 
Example 39
Project: jdk8u60   File: InitialToken.java    License: GNU General Public License v2.0 5 votes vote down vote up
private int getAddrType(InetAddress addr) {
    int addressType = CHANNEL_BINDING_AF_NULL_ADDR;

    if (addr instanceof Inet4Address)
        addressType = CHANNEL_BINDING_AF_INET;
    else if (addr instanceof Inet6Address)
        addressType = CHANNEL_BINDING_AF_INET6;
    return (addressType);
}
 
Example 40
Project: wechatbot-xposed   File: MySocket.java    License: Apache License 2.0 5 votes vote down vote up
public void udpsendmsg(String key, String msg) {
    try {
        Log.i("udp service push", msg);
        Iterator iter = udpClients.entrySet().iterator();
        /*while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                Object val = entry.getValue();

                String[] arr = key.split("\\|\\|\\|");

                byte[] data = msg.getBytes();
                InetAddress address = InetAddress.getByName("127.0.0.1");
                int port = Integer.parseInt(arr[1]);
            Log.i("udp bbb","key = " + address + " and value = " + port);
                DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
                server.send(packet);
        }*/
        if (key == "") {
            key = LastAddress;
        }
        String[] arr = key.split("\\|\\|\\|");

        byte[] data = msg.getBytes();
        InetAddress address = InetAddress.getByName("127.0.0.1");
        int port = Integer.parseInt(arr[1]);
        Log.i("udp bbb", "key = " + address + " and value = " + port);
        DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
        serverudp.send(packet);
    } catch (IOException e) {
        Log.e("udp", e.toString());
        //udpClients.remove(key);
    }

}