Java Code Examples for java.net.InetAddress

The following are top voted examples for showing how to use java.net.InetAddress. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Transwarp-Sample-Code   File: SearchES.java   Source Code and License 8 votes vote down vote up
/**
 * 多字段查询
 */
public static void multisearch() {
    try {
        Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch1").build();
        TransportClient transportClient = TransportClient.builder().
                settings(settings).build().addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("172.16.2.93"), 9300));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("service2","clients");
        SearchResponse searchResponse = searchRequestBuilder.
                setQuery(QueryBuilders.boolQuery()
                        .should(QueryBuilders.termQuery("id","5"))
                        .should(QueryBuilders.prefixQuery("content","oracle")))
                .setFrom(0).setSize(100).setExplain(true).execute().actionGet();
        SearchHits searchHits = searchResponse.getHits();
        System.out.println();
        System.out.println("Total Hits is " + searchHits.totalHits());
        System.out.println();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 2
Project: fdt   File: LocalHost.java   Source Code and License 7 votes vote down vote up
static public List<String> getPublicIPs6() {
    List<String> ips6 = new ArrayList<String>();
    Enumeration<NetworkInterface> ifs;
    try {
        ifs = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        e.printStackTrace();
        return ips6;
    }
    while (ifs.hasMoreElements()) {
        NetworkInterface iface = ifs.nextElement();
        Enumeration<InetAddress> iad = iface.getInetAddresses();
        while (iad.hasMoreElements()) {
            InetAddress localIP = iad.nextElement();
            if (!localIP.isSiteLocalAddress() && !localIP.isLinkLocalAddress() && !localIP.isLoopbackAddress()) {
                if (localIP instanceof java.net.Inet6Address)
                    ips6.add(localIP.getHostAddress());
            }
        }
    }
    return ips6;
}
 
Example 3
Project: googles-monorepo-demo   File: InetAddressesTest.java   Source Code and License 6 votes vote down vote up
public void testForStringIPv6EightColons() throws UnknownHostException {
  String[] eightColons = {
    "::7:6:5:4:3:2:1",
    "::7:6:5:4:3:2:0",
    "7:6:5:4:3:2:1::",
    "0:6:5:4:3:2:1::",
  };

  for (int i = 0; i < eightColons.length; i++) {
    InetAddress ipv6Addr = null;
    // Shouldn't hit DNS, because it's an IP string literal.
    ipv6Addr = InetAddress.getByName(eightColons[i]);
    assertEquals(ipv6Addr, InetAddresses.forString(eightColons[i]));
    assertTrue(InetAddresses.isInetAddress(eightColons[i]));
  }
}
 
Example 4
Project: AeroStory   File: CharSelectedHandler.java   Source Code and License 6 votes vote down vote up
@Override
public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
    int charId = slea.readInt();
    String macs = slea.readMapleAsciiString();
    c.updateMacs(macs);
    if (c.hasBannedMac()) {
        c.getSession().close(true);
        return;
    }

    if (c.getIdleTask() != null) {
        c.getIdleTask().cancel(true);
    }
    c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION);
    String[] socket = Server.getInstance().getIP(c.getWorld(), c.getChannel()).split(":");
    try {
        c.announce(MaplePacketCreator.getServerIP(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1]), charId));
    } catch (UnknownHostException | NumberFormatException e) {
    }
}
 
Example 5
Project: Sem-Update   File: VentanaPrincipal.java   Source Code and License 6 votes vote down vote up
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed
    try {
        // Se intenta conectar, retorna IOException en caso que no pueda
        DatagramSocket clienteSocket = new DatagramSocket();
        byte[] bufferOut = new byte[1000];
        
        String mensajeAMandar = "Mata server" + id;
        bufferOut = mensajeAMandar.getBytes();
        IPServer = InetAddress.getByName(servidor);

        DatagramPacket sendPacket = new DatagramPacket(bufferOut, bufferOut.length, IPServer, numeroPuerto);
        clienteSocket.send(sendPacket);

        jLabel1.setForeground(Color.red);
        clienteSocket.close();
        url.setText("");
        jlabelSQL.setText("");
        this.setTitle("App [ID:?]");
    } catch (IOException ex) {
        System.out.println("(LOG) [ERROR] No se pudo contactar al servidor");
        Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 6
Project: Snakies   File: MainGame.java   Source Code and License 6 votes vote down vote up
public void startClient() {
	if (client != null) {
		Gdx.app.log(TAG, "Looking for server with open UDP port " + Constants.UDP_PORT);
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				InetAddress serverAddress = client.discoverHost(Constants.UDP_PORT, 5000);
				if (serverAddress != null) {
					Gdx.app.log(TAG, "Server discovered at " + serverAddress.getHostAddress());
					try {
						client.connect(5000, serverAddress, Constants.TCP_PORT, Constants.UDP_PORT);
					} catch (IOException e) {
						e.printStackTrace();
						Gdx.app.error(TAG, "Unable to connect to server at " + serverAddress.getHostName());
					}
				} else {
					Gdx.app.log(TAG, "No server found");
				}
			}
		}).start();
	} else {
		Gdx.app.error(TAG, "Trying to start a null-instance client");
	}
}
 
Example 7
Project: BiglyBT   File: BuddyPluginBuddy.java   Source Code and License 6 votes vote down vote up
protected void
setCachedStatus(
	InetAddress		_ip,
	int				_tcp_port,
	int				_udp_port )
{
	setAddress( _ip );

	synchronized( this ){

		if ( current_ip == null ){

			current_ip	= _ip;
			tcp_port	= _tcp_port;
			udp_port	= _udp_port;
		}
	}
}
 
Example 8
Project: ADBToolKitsInstaller   File: MainActivity.java   Source Code and License 6 votes vote down vote up
public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return "0.0.0.0";
}
 
Example 9
Project: JinsMemeBRIDGE-Android   File: MemeOSC.java   Source Code and License 6 votes vote down vote up
public static String getHostIPv4Address() {
  try {
    List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    for (NetworkInterface ni : interfaces) {
      List<InetAddress> addresses = Collections.list(ni.getInetAddresses());
      for (InetAddress addr : addresses) {
        if (!addr.isLoopbackAddress()) {
          String strAddr = addr.getHostAddress();
          if(!strAddr.contains(":")) {
            return strAddr;
          }
        }
      }
    }
  } catch (SocketException e) {
    e.printStackTrace();
  }

  return "0.0.0.0";
}
 
Example 10
Project: WifiChatSharing   File: PrivateChatActivity.java   Source Code and License 6 votes vote down vote up
private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {

            NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();

            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    return ip;
}
 
Example 11
Project: datatree-adapters   File: JsonBson.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
	if (clazz == BigDecimal.class) {
		return (Codec<T>) bigDecimalCodec;
	}
	if (clazz == BigInteger.class) {
		return (Codec<T>) bigIntegerCodec;
	}
	if (clazz == InetAddress.class || clazz == Inet4Address.class || clazz == Inet6Address.class) {
		return (Codec<T>) inetAddressCodec;
	}
	if (clazz.isArray()) {
		return (Codec<T>) arrayCodec;
	}
	return null;
}
 
Example 12
Project: smart_plan   File: Utilty.java   Source Code and License 6 votes vote down vote up
/**
 * 获取手机ip地址,如果WiFi可以,则返回WiFi的ip,否则就返回网络ip.
 *
 * @param context 上下文
 * @return ip
 */
public static String getDeviceNetworkIp(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context
            .CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo != null) {
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {  //wifi
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifi.getConnectionInfo();
            int ip = wifiInfo.getIpAddress();
            return convertToIp(ip);
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // gprs
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
                     en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                         enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        //这里4.0以上部分手机返回的地址将会是ipv6地址,而且在4G下也验证了返回的是
                        //ipv6,而服务器不处理ipv6地址
                        if (!inetAddress.isLoopbackAddress() && !(inetAddress
                                instanceof Inet6Address)) {
                            return inetAddress.getHostAddress().toString();
                        }

                    }

                }
            } catch (SocketException e) {
                Log.e(TAG, "e", e);
            }
        }
    }
    return DEFAULT_NETWORK_IP;
}
 
Example 13
Project: istio-by-example-java   File: HelloworldApplication.java   Source Code and License 6 votes vote down vote up
@GetMapping("/hello/{name}")
public Map<String, String> hello(@Value("${greeting}") String greetingTemplate, @PathVariable String name) throws UnknownHostException {
  Map<String, String> response = new HashMap<>();

  String hostname = InetAddress.getLocalHost().getHostName();
  String greeting = greetingTemplate
      .replaceAll("\\$name", name)
      .replaceAll("\\$hostname", hostname)
      .replaceAll("\\$version", version);

  response.put("greeting", greeting);
  response.put("version", version);
  response.put("hostname", hostname);

  return response;
}
 
Example 14
Project: picocli   File: CommandLineArityTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testNoMissingRequiredParamErrorIfHelpOptionSpecified() {
    class App {
        @Parameters(hidden = true)  // "hidden": don't show this parameter in usage help message
                List<String> allParameters; // no "index" attribute: captures _all_ arguments (as Strings)

        @Parameters(index = "0")    InetAddress  host;
        @Parameters(index = "1")    int          port;
        @Parameters(index = "2..*") File[]       files;

        @Option(names = "-?", help = true) boolean help;
    }
    CommandLine.populateCommand(new App(), new String[] {"-?"});
    try {
        CommandLine.populateCommand(new App(), new String[0]);
        fail("Should not accept missing mandatory parameter");
    } catch (MissingParameterException ex) {
        assertEquals("Missing required parameters: <host>, <port>", ex.getMessage());
    }
}
 
Example 15
Project: lams   File: IPAddressAccessControlHandler.java   Source Code and License 6 votes vote down vote up
@Override
boolean matches(final InetAddress address) {
    byte[] bytes = address.getAddress();
    if (bytes == null) {
        return false;
    }
    if (bytes.length != mask.length) {
        return false;
    }
    for (int i = 0; i < mask.length; ++i) {
        if ((bytes[i] & mask[i]) != prefix[i]) {
            return false;
        }
    }
    return true;
}
 
Example 16
Project: uavstack   File: InetSocketAddressCodec.java   Source Code and License 6 votes vote down vote up
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
    if (object == null) {
        serializer.writeNull();
        return;
    }

    SerializeWriter out = serializer.getWriter();
    InetSocketAddress address = (InetSocketAddress) object;

    InetAddress inetAddress = address.getAddress();

    out.write('{');
    if (inetAddress != null) {
        out.writeFieldName("address");
        serializer.write(inetAddress);
        out.write(',');
    }
    out.writeFieldName("port");
    out.writeInt(address.getPort());
    out.write('}');
}
 
Example 17
Project: GitHub   File: HttpLoggingInterceptorTest.java   Source Code and License 6 votes vote down vote up
@Test public void connectFail() throws IOException {
  setLevel(Level.BASIC);
  client = new OkHttpClient.Builder()
      .dns(new Dns() {
        @Override public List<InetAddress> lookup(String hostname) throws UnknownHostException {
          throw new UnknownHostException("reason");
        }
      })
      .addInterceptor(applicationInterceptor)
      .build();

  try {
    client.newCall(request().build()).execute();
    fail();
  } catch (UnknownHostException expected) {
  }

  applicationLogs
      .assertLogEqual("--> GET " + url)
      .assertLogEqual("<-- HTTP FAILED: java.net.UnknownHostException: reason")
      .assertNoMoreLogs();
}
 
Example 18
Project: fdt   File: LocalHost.java   Source Code and License 6 votes vote down vote up
static public String getPublicIP6() {

        Enumeration<NetworkInterface> ifs;
        try {
            ifs = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }

        while (ifs.hasMoreElements()) {
            NetworkInterface iface = ifs.nextElement();
            Enumeration<InetAddress> iad = iface.getInetAddresses();
            while (iad.hasMoreElements()) {
                InetAddress localIP = iad.nextElement();
                if (!localIP.isSiteLocalAddress() && !localIP.isLinkLocalAddress() && !localIP.isLoopbackAddress()) {
                    if (localIP instanceof java.net.Inet6Address)
                        return localIP.getHostAddress();
                }
            }
        }
        return null;
    }
 
Example 19
Project: d2g-api   File: ServiceInformation.java   Source Code and License 5 votes vote down vote up
public ServiceInformation(Exception e){
    this.errorCode= D2GBaseExceptionCodes.SOMETHING_WENT_WRONG.getId();
    this.errorMessage= D2GBaseExceptionCodes.SOMETHING_WENT_WRONG.getErrorMessage();
    try {
        this.nodeId= String.valueOf(InetAddress.getLocalHost());
    } catch (UnknownHostException error) {
        this.nodeId="Can not resolve server address";
    }
    this.timestamp=new Date().getTime()/1000;
}
 
Example 20
Project: T0rlib4Android   File: InetRange.java   Source Code and License 5 votes vote down vote up
/**
 * Adds another ip for this range.
 * 
 * @param ip
 *            IP os the host which should be added to this range.
 */
public synchronized void add(final InetAddress ip) {
	long from, to;
	from = to = ip2long(ip);
	all.addElement(new Object[] { ip.getHostName(), ip, new Long(from),
			new Long(to) });
}
 
Example 21
Project: ZooKeeper   File: ZooKeeperServerBean.java   Source Code and License 5 votes vote down vote up
public String getClientPort() {
    try {
        return InetAddress.getLocalHost().getHostAddress() + ":"
            + zks.getClientPort();
    } catch (UnknownHostException e) {
        return "localhost:" + zks.getClientPort();
    }
}
 
Example 22
Project: OpenJSharp   File: Krb5InitCredential.java   Source Code and License 5 votes vote down vote up
private Krb5InitCredential(Krb5NameElement name,
                           Credentials delegatedCred,
                           byte[] asn1Encoding,
                           KerberosPrincipal client,
                           KerberosPrincipal server,
                           byte[] sessionKey,
                           int keyType,
                           boolean[] flags,
                           Date authTime,
                           Date startTime,
                           Date endTime,
                           Date renewTill,
                           InetAddress[] clientAddresses)
                           throws GSSException {
    super(asn1Encoding,
          client,
          server,
          sessionKey,
          keyType,
          flags,
          authTime,
          startTime,
          endTime,
          renewTill,
          clientAddresses);

    this.name = name;
    // A delegated cred does not have all fields set. So do not try to
    // creat new Credentials out of the delegatedCred.
    this.krb5Credentials = delegatedCred;
}
 
Example 23
Project: cas-server-4.2.1   File: ReverseDNSRunnable.java   Source Code and License 5 votes vote down vote up
/**
 * Runnable implementation to thread the work done in this class, allowing the
 * implementer to set a thread timeout and thereby short-circuit the lookup.
 */
@Override
public void run() {
    try {
        LOGGER.debug("Attempting to resolve {}", this.ipAddress);
        final InetAddress address = InetAddress.getByName(this.ipAddress);
        set(address.getCanonicalHostName());
    } catch (final UnknownHostException e) {
        /** N/A -- Default to IP address, but that's already done. **/
        LOGGER.debug("Unable to identify the canonical hostname for ip address.", e);
    }
}
 
Example 24
Project: cas-5.1.0   File: MaxmindDatabaseGeoLocationService.java   Source Code and License 5 votes vote down vote up
@Override
public GeoLocationResponse locate(final String address) {
    try {
        return locate(InetAddress.getByName(address));
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
 
Example 25
Project: boutique-de-jus   File: SignalTransceiver.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a transceiver and waits for receiving a stop signal. The method blocks until the future passed
 * to the preparation consumer is completed. It's up to the consumer on which event the transceiver should stop
 * @param address
 *  the address to listen for packets
 * @param listenPort
 *  the port to listen for packets (UDP)
 * @param prepare
 *  a consumer that gets the instance of the transceiver in order to setup proper actions on receiving events
 */
public static void acceptAndWait(InetAddress address, int listenPort, BiConsumer<SignalTransceiver, CompletableFuture<Event>> prepare){
    try (SignalTransceiver com = SignalTransceiver.create(address, listenPort).start()) {
        CompletableFuture<Event> stopListening = new CompletableFuture<>();
        prepare.accept(com, stopListening);
        while (!stopListening.isDone() || stopListening.isCancelled()) {
            Thread.sleep(150);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failure to receive signals", e);
    }
}
 
Example 26
Project: LightSIP   File: ConnectionOrientedMessageChannel.java   Source Code and License 5 votes vote down vote up
public void processMessage(SIPMessage sipMessage, InetAddress address) {
    this.peerAddress = address;
    try {
        processMessage(sipMessage);
    } catch (Exception e) {
        if (logger.isLoggingEnabled(
                ServerLog.TRACE_ERROR)) {
            logger.logError(
                    "ERROR processing self routing", e);
        }
    }
}
 
Example 27
Project: BiglyBT   File: UPnPSSDPListener.java   Source Code and License 5 votes vote down vote up
public void
receivedResult(
	NetworkInterface	network_interface,
	InetAddress			local_address,
	InetAddress			originator,
	String				USN,
	URL					location,
	String				ST,
	String				AL );
 
Example 28
Project: incubator-servicecomb-saga   File: ServiceConfig.java   Source Code and License 5 votes vote down vote up
public ServiceConfig(String serviceName) {
  this.serviceName = serviceName;
  try {
    instanceId = serviceName + "-" + InetAddress.getLocalHost().getHostAddress();
  } catch (UnknownHostException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 29
Project: nifi-tools   File: SocksProxySocketFactory.java   Source Code and License 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
Project: monarch   File: AbstractDistributionConfig.java   Source Code and License 5 votes vote down vote up
public static final InetAddress _getDefaultMcastAddress() {
  // Default MCast address can be just IPv4 address.
  // On IPv6 machines, JGroups converts IPv4 address to equivalent IPv6 address.
  String ipLiteral = "239.192.81.1";
  try {
    return InetAddress.getByName(ipLiteral);
  } catch (UnknownHostException ex) {
    // this should never happen
    throw new Error(
        LocalizedStrings.AbstractDistributionConfig_UNEXPECTED_PROBLEM_GETTING_INETADDRESS_0
            .toLocalizedString(ex),
        ex);
  }
}
 
Example 31
Project: galop   File: ProxyConfigurationImplTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
    port = new PortNumber(8080);
    backlogSize = 50;
    bindAddress = mock(InetAddress.class);
    configuration = new ProxyConfigurationImpl(port, backlogSize, bindAddress);
}
 
Example 32
Project: NSS   File: ClientControl.java   Source Code and License 5 votes vote down vote up
public void sendPingMessage2(int pingId,InetAddress dstIp,int dstPort){
	PingMessage2 lm=new PingMessage2(0,route.localclientId,pingId);
	lm.setDstAddress(dstIp);
	lm.setDstPort(dstPort);
	try {
		sendPacket(lm.getDatagramPacket());
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 33
Project: jdk8u-jdk   File: InitialToken.java   Source Code and License 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 34
Project: Reer   File: TcpIncomingConnector.java   Source Code and License 5 votes vote down vote up
public ConnectionAcceptor accept(Action<ConnectCompletion> action, boolean allowRemote) {
    final ServerSocketChannel serverSocket;
    int localPort;
    try {
        serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(addressFactory.getLocalBindingAddress(), 0));
        localPort = serverSocket.socket().getLocalPort();
    } catch (Exception e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }

    UUID id = idGenerator.generateId();
    List<InetAddress> addresses = addressFactory.getCommunicationAddresses();
    final Address address = new MultiChoiceAddress(id, localPort, addresses);
    LOGGER.debug("Listening on {}.", address);

    final StoppableExecutor executor = executorFactory.create("Incoming " + (allowRemote ? "remote" : "local")+ " TCP Connector on port " + localPort);
    executor.execute(new Receiver(serverSocket, action, allowRemote));

    return new ConnectionAcceptor() {
        public Address getAddress() {
            return address;
        }

        public void requestStop() {
            CompositeStoppable.stoppable(serverSocket).stop();
        }

        public void stop() {
            requestStop();
            executor.stop();
        }
    };
}
 
Example 35
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: MixAllTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetLocalInetAddress() throws Exception {
    List<String> localInetAddress = MixAll.getLocalInetAddress();
    String local = InetAddress.getLocalHost().getHostAddress();
    assertThat(localInetAddress).contains("127.0.0.1");
    assertThat(localInetAddress).contains(local);
}
 
Example 36
Project: jdk8u-jdk   File: SimpleNode.java   Source Code and License 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 37
Project: flume-release-1.7.0   File: TestTwitterSource.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setUp() {
  try {
    Assume.assumeNotNull(InetAddress.getByName("stream.twitter.com"));
  } catch (UnknownHostException e) {
    Assume.assumeTrue(false); // ignore Test if twitter is unreachable
  }
}
 
Example 38
Project: reading-and-annotate-rocketmq-3.4.6   File: MixAllTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws Exception {
    List<String> localInetAddress = MixAll.getLocalInetAddress();
    String local = InetAddress.getLocalHost().getHostAddress();
    Assert.assertTrue(localInetAddress.contains("127.0.0.1"));
    Assert.assertTrue(localInetAddress.contains(local));
}
 
Example 39
Project: stynico   File: Utll.java   Source Code and License 5 votes vote down vote up
public static InetAddress intToInet(int value) {
	byte[] bytes = new byte[4];
	for(int i = 0; i<4; i++) {
		bytes[i] = byteOfInt(value, i);
	}
	try {
		return InetAddress.getByAddress(bytes);
	} catch (UnknownHostException e) {
		// This only happens if the byte array has a bad length
		return null;
	}
}
 
Example 40
Project: candlelight   File: NetworkEngine.java   Source Code and License 5 votes vote down vote up
public void addPublicEndpoint(InetAddress address, int port)
{
	synchronized (this.endpoints)
	{
		final EventLoopGroup boss = new NioEventLoopGroup();
		final EventLoopGroup worker = new NioEventLoopGroup();
		final ServerBootstrap b = new ServerBootstrap()
				.group(boss, worker)
				.childHandler(new ChannelInitializer<Channel>() {
					@Override
					protected void initChannel(Channel ch) throws Exception
					{
						final PacketRegistry registry = NetworkEngine.this.packetRegistry;
						final NetworkDispatcher dispatch = new NetworkDispatcher(
								NetworkEngine.this, NetworkSide.SERVER);
						NetworkEngine.this.dispatchers.add(dispatch);

						ch.pipeline()
								.addLast(new VarInt21FrameDecoder())
								.addLast(new PacketDecoder(NetworkSide.SERVER, registry))
								.addLast(new VarInt21FrameEncoder())
								.addLast(new PacketEncoder(NetworkSide.CLIENT, registry))
								.addLast(dispatch);
					}
				})
				.channel(NioServerSocketChannel.class);

		//Host and wait until done
		b.localAddress(address, port).bind().syncUninterruptibly();
	}
}
 
Example 41
Project: hrrs   File: ApacheHttpClientFactory.java   Source Code and License 5 votes vote down vote up
private void setLocalAddress(RequestConfig.Builder builder) {
    String localAddress = config.getLocalAddress();
    if (localAddress != null) {
        try {
            InetAddress localInetAddress = InetAddress.getByName(localAddress);
            builder.setLocalAddress(localInetAddress);
        } catch (UnknownHostException error) {
            String message = String.format("failed reading IP address (localAddress=%s)", localAddress);
            throw new RuntimeException(message, error);
        }
    }
}
 
Example 42
Project: strictfp-back-end   File: SafeCheck.java   Source Code and License 5 votes vote down vote up
private ArrayList<String> getAllIP(String host) throws UnknownHostException {
	ArrayList<String> ips = new ArrayList<>();
	InetAddress[] addresses = InetAddress.getAllByName(host);
	for (InetAddress thisInetAddress : addresses)
		ips.add(thisInetAddress.getHostAddress());
	return ips;
}
 
Example 43
Project: okwallet   File: PeerListFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onLoadFinished(final Loader<String> loader, final String hostname) {
    final InetAddress address = ((ReverseDnsLoader) loader).address;
    hostnames.put(address, hostname);

    loaderManager.destroyLoader(ID_REVERSE_DNS_LOADER);
}
 
Example 44
Project: BiglyBT   File: NetworkAdminProtocol.java   Source Code and License 5 votes vote down vote up
public InetAddress
test(
	NetworkAdminNetworkInterfaceAddress	address,
	boolean								upnp_map,
	NetworkAdminProgressListener		listener )

	throws NetworkAdminException;
 
Example 45
Project: CleanBT   File: Utils.java   Source Code and License 5 votes vote down vote up
static InetAddress getAddrFromBytes(byte[] bytes) {
    try {
        return InetAddress.getByAddress(bytes);
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 46
Project: BedrockProxy   File: RakNetUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Parses a single String as an address and port and converts it to an
 * <code>InetSocketAddress</code>.
 *
 * @param address     the address to convert.
 * @param defaultPort the default port to use if one is not specified.
 * @return the parsed <code>InetSocketAddress</code>.
 * @throws UnknownHostException if the address is in an invalid format or if the host cannot
 *                              be found.
 */
public static InetSocketAddress parseAddress(String address, int defaultPort) throws UnknownHostException {
    String[] addressSplit = address.split(":");
    if (addressSplit.length == 1 || addressSplit.length == 2) {
        InetAddress inetAddress = InetAddress.getByName(addressSplit[0]);
        int port = (addressSplit.length == 2 ? parseIntPassive(addressSplit[1]) : defaultPort);
        if (port >= 0 && port <= 65535) {
            return new InetSocketAddress(inetAddress, port);
        } else {
            throw new UnknownHostException("Port number must be between 0-65535");
        }
    } else {
        throw new UnknownHostException("Format must follow address:port");
    }
}
 
Example 47
Project: jdk8u-jdk   File: ChangeHostName.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        InetAddress localAddress = InetAddress.getLocalHost();
        String[] hostlist = new String[] {
            localAddress.getHostAddress(), localAddress.getHostName() };

        for (int i = 0; i < hostlist.length; i++) {

            System.setProperty("java.rmi.server.hostname", hostlist[i]);
            Remote impl = new ChangeHostName();
            System.err.println("\ncreated impl extending URO: " + impl);

            Receiver stub = (Receiver) RemoteObject.toStub(impl);
            System.err.println("stub for impl: " + stub);

            System.err.println("invoking method on stub");
            stub.receive(stub);

            UnicastRemoteObject.unexportObject(impl, true);
            System.err.println("unexported impl");

            if (stub.toString().indexOf(hostlist[i]) >= 0) {
                System.err.println("stub's ref contains hostname: " +
                                   hostlist[i]);
            } else {
                throw new RuntimeException(
                    "TEST FAILED: stub's ref doesn't contain hostname: " +
                    hostlist[i]);
            }
        }
        System.err.println("TEST PASSED");
    }
 
Example 48
Project: open-rmbt   File: Helperfunctions.java   Source Code and License 5 votes vote down vote up
public static Name getReverseIPName(final InetAddress adr, final Name postfix)
{
    final byte[] addr = adr.getAddress();
    final StringBuilder sb = new StringBuilder();
    if (addr.length == 4)
        for (int i = addr.length - 1; i >= 0; i--)
        {
            sb.append(addr[i] & 0xFF);
            if (i > 0)
                sb.append(".");
        }
    else
    {
        final int[] nibbles = new int[2];
        for (int i = addr.length - 1; i >= 0; i--)
        {
            nibbles[0] = (addr[i] & 0xFF) >> 4;
            nibbles[1] = addr[i] & 0xFF & 0xF;
            for (int j = nibbles.length - 1; j >= 0; j--)
            {
                sb.append(Integer.toHexString(nibbles[j]));
                if (i > 0 || j > 0)
                    sb.append(".");
            }
        }
    }
    try
    {
        return Name.fromString(sb.toString(), postfix);
    }
    catch (final TextParseException e)
    {
        throw new IllegalStateException("name cannot be invalid");
    }
}
 
Example 49
Project: hadoop   File: TestSecurityUtil.java   Source Code and License 5 votes vote down vote up
private void verify(String original, String hostname, String expected)
    throws IOException {
  assertEquals(expected,
               SecurityUtil.getServerPrincipal(original, hostname));

  InetAddress addr = mockAddr(hostname);
  assertEquals(expected,
               SecurityUtil.getServerPrincipal(original, addr));
}
 
Example 50
Project: taskwarrior-java-client   File: TaskwarriorPropertiesConfiguration.java   Source Code and License 5 votes vote down vote up
@Override
public InetAddress getServerHost() {
    String host = getExistingProperty(PROPERTY_TASKWARRIOR_SERVER_HOST);
    try {
        return InetAddress.getByName(host);
    } catch (UnknownHostException e) {
        throw new TaskwarriorConfigurationException(e, "Cannot resolve host address '%s': %s", host, e.getMessage());
    }
}
 
Example 51
Project: oscm   File: UserNotificationIT.java   Source Code and License 5 votes vote down vote up
private String retrieveComputerName() {
    try {
        String hostName = InetAddress.getLocalHost().getHostName();
        if (hostName.indexOf('.') > 0) {
            hostName = hostName.substring(0, hostName.indexOf('.'));
        }
        return hostName;
    } catch (UnknownHostException e) {
        return "";
    }
}
 
Example 52
Project: Nird2   File: LanTcpPluginTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testIncomingKeyAgreementConnection() throws Exception {
	if (!systemHasLocalIpv4Address()) {
		System.err.println("WARNING: Skipping test, no local IPv4 address");
		return;
	}
	Callback callback = new Callback();
	Executor executor = Executors.newCachedThreadPool();
	DuplexPlugin plugin = new LanTcpPlugin(executor, backoff, callback,
			0, 0);
	plugin.start();
	assertTrue(callback.propertiesLatch.await(5, SECONDS));
	KeyAgreementListener kal =
			plugin.createKeyAgreementListener(new byte[COMMIT_LENGTH]);
	assertNotNull(kal);
	Callable<KeyAgreementConnection> c = kal.listen();
	FutureTask<KeyAgreementConnection> f =
			new FutureTask<KeyAgreementConnection>(c);
	new Thread(f).start();
	// The plugin should have bound a socket and stored the port number
	BdfList descriptor = kal.getDescriptor();
	assertEquals(3, descriptor.size());
	assertEquals(TRANSPORT_ID_LAN, descriptor.getLong(0).longValue());
	byte[] address = descriptor.getRaw(1);
	InetAddress addr = InetAddress.getByAddress(address);
	assertTrue(addr instanceof Inet4Address);
	assertFalse(addr.isLoopbackAddress());
	assertTrue(addr.isLinkLocalAddress() || addr.isSiteLocalAddress());
	int port = descriptor.getLong(2).intValue();
	assertTrue(port > 0 && port < 65536);
	// The plugin should be listening on the port
	InetSocketAddress socketAddr = new InetSocketAddress(addr, port);
	Socket s = new Socket();
	s.connect(socketAddr, 100);
	assertNotNull(f.get(5, SECONDS));
	s.close();
	kal.close();
	// Stop the plugin
	plugin.stop();
}
 
Example 53
Project: T0rlib4Android   File: SocksSocket.java   Source Code and License 5 votes vote down vote up
/**
 * Get remote host as InetAddress object, might return null if addresses are
 * resolved by proxy, and it is not possible to resolve it locally
 * 
 * @return Ip address of the host this socket is connected to, or null if
 *         address was returned by the proxy as DOMAINNAME and can't be
 *         resolved locally.
 */
public InetAddress getInetAddress() {
	if (remoteIP == null) {
		try {
			remoteIP = InetAddress.getByName(remoteHost);
		} catch (final UnknownHostException e) {
			return null;
		}
	}
	return remoteIP;
}
 
Example 54
Project: okwallet   File: PeerListFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            adapter.notifyDataSetChanged();

            final Loader<String> loader = loaderManager.getLoader(ID_REVERSE_DNS_LOADER);
            final boolean loaderRunning = loader != null && loader.isStarted();

            if (!loaderRunning) {
                for (int i = 0; i < adapter.getItemCount(); i++) {
                    final Peer peer = adapter.getItem(i);
                    final InetAddress address = peer.getAddress().getAddr();

                    if (!hostnames.containsKey(address)) {
                        final Bundle args = new Bundle();
                        args.putSerializable("address", address);
                        loaderManager.initLoader(ID_REVERSE_DNS_LOADER, args, reverseDnsLoaderCallbacks)
                                .forceLoad();

                        break;
                    }
                }
            }

            handler.postDelayed(this, REFRESH_MS);
        }
    }, REFRESH_MS);
}
 
Example 55
Project: Proyecto-DASI   File: UDPSocketHelper.java   Source Code and License 5 votes vote down vote up
/** Create a UDP heart beat object.
 * @param address address of the monitor to which to send the signal 
 * @param port port number the monitor will be listening on
 * @param intervalMs preferred time, in milliseconds, between signals.
 */
public UDPHeartBeat(InetAddress address, int port, int intervalMs)
{
    this.address = address;
    this.port = port;
    this.intervalMs = intervalMs;
}
 
Example 56
Project: elasticsearch_my   File: InetAddressesTests.java   Source Code and License 5 votes vote down vote up
public void testConvertDottedQuadToHex() throws UnknownHostException {
    String[] ipStrings = {"7::0.128.0.127", "7::0.128.0.128",
            "7::128.128.0.127", "7::0.128.128.127"};

    for (String ipString : ipStrings) {
        // Shouldn't hit DNS, because it's an IP string literal.
        InetAddress ipv6Addr = InetAddress.getByName(ipString);
        assertEquals(ipv6Addr, InetAddresses.forString(ipString));
        assertTrue(InetAddresses.isInetAddress(ipString));
    }
}
 
Example 57
Project: monarch   File: PartitionedRegionLoadModelJUnitTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test to make sure that moving buckets honors size restrictions for VMs.
 */
@Test
public void testMoveBucketsWithSizeLimits() throws Exception {
  PartitionedRegionLoadModel model = new PartitionedRegionLoadModel(bucketOperator, 0, 6,
      getAddressComparor(false), Collections.<InternalDistributedMember>emptySet(), null);
  InternalDistributedMember member1 =
      new InternalDistributedMember(InetAddress.getByName("127.0.0.1"), 1);
  InternalDistributedMember member2 =
      new InternalDistributedMember(InetAddress.getByName("127.0.0.1"), 2);
  InternalDistributedMember member3 =
      new InternalDistributedMember(InetAddress.getByName("127.0.0.1"), 3);
  // Create some imbalanced nodes
  PartitionMemberInfoImpl details1 = buildDetails(member1, 50, 50,
      new long[] {30, 30, 30, 0, 0, 0}, new long[] {1, 1, 1, 0, 0, 0});
  PartitionMemberInfoImpl details2 = buildDetails(member2, 50, 50,
      new long[] {0, 0, 0, 10, 10, 10}, new long[] {0, 0, 0, 1, 1, 1});
  // this member has a lower size that can't fit buckets of size 30
  PartitionMemberInfoImpl details3 =
      buildDetails(member3, 50, 20, new long[] {0, 0, 0, 0, 0, 0}, new long[] {0, 0, 0, 0, 0, 0});
  model.addRegion("a", Arrays.asList(details1, details2, details3), new FakeOfflineDetails(),
      true);

  assertEquals(3, doMoves(new CompositeDirector(false, false, true, true), model));

  assertEquals(Collections.emptyList(), bucketOperator.creates);

  // One bucket should move from each member to member4
  Set<Move> expectedMoves = new HashSet<Move>();
  expectedMoves.add(new Move(member1, member2));
  expectedMoves.add(new Move(member2, member3));
  expectedMoves.add(new Move(member2, member3));

  assertEquals(expectedMoves, new HashSet<Move>(bucketOperator.bucketMoves));

  Set<PartitionMemberInfo> detailSet = model.getPartitionedMemberDetails("a");
  for (PartitionMemberInfo member : detailSet) {
    assertEquals(2, member.getPrimaryCount());
    assertEquals(2, member.getBucketCount());
  }
}
 
Example 58
Project: OpenJSharp   File: SctpNet.java   Source Code and License 4 votes vote down vote up
static native void setPrimAddrOption0(int fd, int assocId, InetAddress ia,
int port) throws IOException;
 
Example 59
Project: T0rlib4Android   File: Socks4Message.java   Source Code and License 4 votes vote down vote up
/**
 * Server successfull reply
 */
public Socks4Message(final int cmd, final InetAddress ip, final int port) {
	this(0, cmd, ip, port, null);
}
 
Example 60
Project: ditb   File: TestThriftServerCmdLine.java   Source Code and License 4 votes vote down vote up
@Test(timeout=600000)
public void testRunThriftServer() throws Exception {
  List<String> args = new ArrayList<String>();
  if (implType != null) {
    String serverTypeOption = implType.toString();
    assertTrue(serverTypeOption.startsWith("-"));
    args.add(serverTypeOption);
  }
  port = HBaseTestingUtility.randomFreePort();
  args.add("-" + ThriftServer.PORT_OPTION);
  args.add(String.valueOf(port));
  if (specifyFramed) {
    args.add("-" + ThriftServer.FRAMED_OPTION);
  }
  if (specifyBindIP) {
    args.add("-" + ThriftServer.BIND_OPTION);
    args.add(InetAddress.getLocalHost().getHostName());
  }
  if (specifyCompact) {
    args.add("-" + ThriftServer.COMPACT_OPTION);
  }
  args.add("start");

  thriftServer = new ThriftServer(TEST_UTIL.getConfiguration());
  startCmdLineThread(args.toArray(new String[args.size()]));

  // wait up to 10s for the server to start
  for (int i = 0; i < 100
      && (thriftServer.serverRunner == null || thriftServer.serverRunner.tserver == null); i++) {
    Thread.sleep(100);
  }

  Class<? extends TServer> expectedClass = implType != null ?
      implType.serverClass : TBoundedThreadPoolServer.class;
  assertEquals(expectedClass,
               thriftServer.serverRunner.tserver.getClass());

  try {
    talkToThriftServer();
  } catch (Exception ex) {
    clientSideException = ex;
  } finally {
    stopCmdLineThread();
  }

  if (clientSideException != null) {
    LOG.error("Thrift client threw an exception. Parameters:" +
        getParametersString(), clientSideException);
    throw new Exception(clientSideException);
  }
}