/** * 多字段查询 */ 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(); } }
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])); } }
@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) { } }
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); } }
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"); } }
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; } } }
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"; }
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"; }
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; }
@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; }
/** * 获取手机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; }
@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; }
@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()); } }
@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; }
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('}'); }
@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(); }
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; }
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; }
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; }
/** * 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) }); }
public String getClientPort() { try { return InetAddress.getLocalHost().getHostAddress() + ":" + zks.getClientPort(); } catch (UnknownHostException e) { return "localhost:" + zks.getClientPort(); } }
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; }
/** * 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); } }
@Override public GeoLocationResponse locate(final String address) { try { return locate(InetAddress.getByName(address)); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
/** * 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); } }
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); } } }
public void receivedResult( NetworkInterface network_interface, InetAddress local_address, InetAddress originator, String USN, URL location, String ST, String AL );
public ServiceConfig(String serviceName) { this.serviceName = serviceName; try { instanceId = serviceName + "-" + InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { throw new IllegalStateException(e); } }
@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; }
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); } }
@Before public void setUp() { port = new PortNumber(8080); backlogSize = 50; bindAddress = mock(InetAddress.class); configuration = new ProxyConfigurationImpl(port, backlogSize, bindAddress); }
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(); } }
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); }
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(); } }; }
@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); }
/** * 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 */ } }
@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 } }
@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)); }
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; } }
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(); } }