當前位置: 首頁>>代碼示例>>Java>>正文


Java InetAddress類代碼示例

本文整理匯總了Java中java.net.InetAddress的典型用法代碼示例。如果您正苦於以下問題:Java InetAddress類的具體用法?Java InetAddress怎麽用?Java InetAddress使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


InetAddress類屬於java.net包,在下文中一共展示了InetAddress類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: multisearch

import java.net.InetAddress; //導入依賴的package包/類
/**
 * 多字段查詢
 */
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();
    }
}
 
開發者ID:Transwarp-DE,項目名稱:Transwarp-Sample-Code,代碼行數:24,代碼來源:SearchES.java

示例2: testForStringIPv6EightColons

import java.net.InetAddress; //導入依賴的package包/類
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]));
  }
}
 
開發者ID:paul-hammant,項目名稱:googles-monorepo-demo,代碼行數:17,代碼來源:InetAddressesTest.java

示例3: handlePacket

import java.net.InetAddress; //導入依賴的package包/類
@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) {
    }
}
 
開發者ID:NovaStory,項目名稱:AeroStory,代碼行數:21,代碼來源:CharSelectedHandler.java

示例4: jButtonDetenerActionPerformed

import java.net.InetAddress; //導入依賴的package包/類
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);
    }
}
 
開發者ID:AmauryOrtega,項目名稱:Sem-Update,代碼行數:24,代碼來源:VentanaPrincipal.java

示例5: startClient

import java.net.InetAddress; //導入依賴的package包/類
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");
	}
}
 
開發者ID:tonyzhang617,項目名稱:Snakies,代碼行數:27,代碼來源:MainGame.java

示例6: setCachedStatus

import java.net.InetAddress; //導入依賴的package包/類
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;
		}
	}
}
 
開發者ID:BiglySoftware,項目名稱:BiglyBT,代碼行數:19,代碼來源:BuddyPluginBuddy.java

示例7: getLocalIpAddress

import java.net.InetAddress; //導入依賴的package包/類
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";
}
 
開發者ID:Crixec,項目名稱:ADBToolKitsInstaller,代碼行數:17,代碼來源:MainActivity.java

示例8: getHostIPv4Address

import java.net.InetAddress; //導入依賴的package包/類
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";
}
 
開發者ID:tkrworks,項目名稱:JinsMemeBRIDGE-Android,代碼行數:21,代碼來源:MemeOSC.java

示例9: getIpAddress

import java.net.InetAddress; //導入依賴的package包/類
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;
}
 
開發者ID:yuvaraj119,項目名稱:WifiChatSharing,代碼行數:24,代碼來源:PrivateChatActivity.java

示例10: get

import java.net.InetAddress; //導入依賴的package包/類
@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;
}
 
開發者ID:berkesa,項目名稱:datatree-adapters,代碼行數:18,代碼來源:JsonBson.java

示例11: getDeviceNetworkIp

import java.net.InetAddress; //導入依賴的package包/類
/**
 * 獲取手機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;
}
 
開發者ID:facetome,項目名稱:smart_plan,代碼行數:42,代碼來源:Utilty.java

示例12: hello

import java.net.InetAddress; //導入依賴的package包/類
@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;
}
 
開發者ID:saturnism,項目名稱:istio-by-example-java,代碼行數:17,代碼來源:HelloworldApplication.java

示例13: testNoMissingRequiredParamErrorIfHelpOptionSpecified

import java.net.InetAddress; //導入依賴的package包/類
@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());
    }
}
 
開發者ID:remkop,項目名稱:picocli,代碼行數:21,代碼來源:CommandLineArityTest.java

示例14: matches

import java.net.InetAddress; //導入依賴的package包/類
@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;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:17,代碼來源:IPAddressAccessControlHandler.java

示例15: write

import java.net.InetAddress; //導入依賴的package包/類
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('}');
}
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:22,代碼來源:InetSocketAddressCodec.java


注:本文中的java.net.InetAddress類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。