本文整理汇总了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();
}
}
示例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]));
}
}
示例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) {
}
}
示例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);
}
}
示例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");
}
}
示例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;
}
}
}
示例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";
}
示例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";
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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());
}
}
示例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;
}
示例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('}');
}