Tabnine Logo
InetAddress
Code IndexAdd Tabnine to your IDE (free)

How to use
InetAddress
in
java.net

Best Java code snippets using java.net.InetAddress (Showing top 20 results out of 47,241)

Refine searchRefine arrow

  • InetSocketAddress
  • Socket
  • NetworkInterface
  • Enumeration
  • ServerSocket
  • InputStreamReader
  • BufferedReader
  • PrintWriter
  • InterfaceAddress
origin: gocd/gocd

private static boolean isLocalhostWithNonLoopbackIpAddress(String ipAddress) {
  for (NetworkInterface networkInterface : localInterfaces) {
    Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();
    while (inetAddressEnumeration.hasMoreElements()) {
      InetAddress address = inetAddressEnumeration.nextElement();
      if (!address.isLoopbackAddress() && ipAddress.equalsIgnoreCase(address.getHostAddress())) {
        return true;
      }
    }
  }
  return false;
}
origin: dropwizard/dropwizard

  @Override
  OutputStream openNewOutputStream() throws IOException {
    final Socket socket = socketFactory.createSocket();
    // Prevent automatic closing of the connection during periods of inactivity.
    socket.setKeepAlive(true);
    // Important not to cache `InetAddress` in case the host moved to a new IP address.
    socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), connectionTimeoutMs);
    return new BufferedOutputStream(socket.getOutputStream(), sendBufferSize);
  }
}
origin: iluwatar/java-design-patterns

@Override
public void run() {
 try (Socket socket = new Socket(InetAddress.getLocalHost(), serverPort)) {
  OutputStream outputStream = socket.getOutputStream();
  PrintWriter writer = new PrintWriter(outputStream);
  sendLogRequests(writer, socket.getInputStream());
 } catch (IOException e) {
  LOGGER.error("error sending requests", e);
  throw new RuntimeException(e);
 }
}
origin: spring-projects/spring-framework

private InetAddress getLocalHost() {
  try {
    return InetAddress.getLocalHost();
  }
  catch (UnknownHostException ex) {
    return InetAddress.getLoopbackAddress();
  }
}
origin: ctripcorp/apollo

public String getLocalHostName() {
 try {
  if (null == m_localHost) {
   m_localHost = InetAddress.getLocalHost();
  }
  return m_localHost.getHostName();
 } catch (UnknownHostException e) {
  return m_local.getHostName();
 }
}
origin: spring-projects/spring-framework

private static String generateId() {
  String host;
  try {
    host = InetAddress.getLocalHost().getHostAddress();
  }
  catch (UnknownHostException ex) {
    host = "unknown";
  }
  return host + '-' + UUID.randomUUID();
}
origin: apache/zookeeper

LOG.info("connecting to {} {}", host, port);
Socket sock;
InetSocketAddress hostaddress= host != null ? new InetSocketAddress(host, port) :
  new InetSocketAddress(InetAddress.getByName(null), port);
if (secure) {
  LOG.info("using secure socket");
  sock = new Socket();
  sock.connect(hostaddress, timeout);
sock.setSoTimeout(timeout);
BufferedReader reader = null;
try {
      new BufferedReader(
          new InputStreamReader(sock.getInputStream()));
  StringBuilder sb = new StringBuilder();
  String line;
  while((line = reader.readLine()) != null) {
    sb.append(line + "\n");
  sock.close();
  if (reader != null) {
    reader.close();
origin: stackoverflow.com

InetAddress address=InetAddress.getLocalHost();
Socket s1=null;
String line=null;
  s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
  br= new BufferedReader(new InputStreamReader(System.in));
  is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
  os= new PrintWriter(s1.getOutputStream());
  line=br.readLine(); 
  while(line.compareTo("QUIT")!=0){
      os.println(line);
      os.flush();
      response=is.readLine();
      System.out.println("Server Response : "+response);
origin: igniterealtime/Openfire

if (interfaceName != null) {
  if (interfaceName.trim().length() > 0) {
    bindInterface = InetAddress.getByName(interfaceName);
serverSocket = new ServerSocket(port, -1, bindInterface);
Log.debug("Flash cross domain is listening on " + interfaceName + " on port " + port);
BufferedReader in = null;
try {
  clientSocket = serverSocket.accept();
  clientSocket.setSoTimeout(10000); // 10 second timeout
  out = new PrintWriter(clientSocket.getOutputStream(), true);
  in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    out.write(CROSS_DOMAIN_TEXT +
        XMPPServer.getInstance().getConnectionManager().getClientListenerPort() +
        CROSS_DOMAIN_END_TEXT+"\u0000");
    out.flush();
    out.close();
    in.close();
origin: apache/cloudstack

  port = NumbersUtil.parseInt(args[1], port);
InetAddress addr = InetAddress.getByName(hostname);
try(Socket socket = new Socket(addr, port);
  PrintWriter out = new PrintWriter(socket.getOutputStream(), true);)
  java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
  String validationWord = "cloudnine";
  String validationInput = "";
  while (!validationWord.equals(validationInput)) {
    System.out.print("Enter Validation Word:");
    validationInput = stdin.readLine();
    System.out.println();
  String input = stdin.readLine();
  if (input != null) {
    out.println(input);
origin: org.codehaus.groovy/groovy

GroovyClientConnection(Script script, boolean autoOutput,Socket socket) throws IOException {
  this.script = script;
  this.autoOutputFlag = autoOutput;
  this.socket = socket;
  reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  writer = new PrintWriter(socket.getOutputStream());
  new Thread(this, "Groovy client connection - " + socket.getInetAddress().getHostAddress()).start();
}
public void run() {
origin: cSploit/android

int read = 0;
final String client = mSocket.getInetAddress().getHostAddress();
 BufferedReader bReader = new BufferedReader(new InputStreamReader(byteArrayInputStream));
 StringBuilder builder = new StringBuilder();
 String line = null;
 boolean headersProcessed = false;
 while((line = bReader.readLine()) != null){
  if(headersProcessed == false){
   headers.add(line);
  mWriter = new BufferedOutputStream(mSocket.getOutputStream());
   mWriter.close();
  } else{
   mServerReader = mServer.getInputStream();
   mServerWriter = mServer.getOutputStream();
origin: glyptodon/guacamole-client

SocketAddress address = new InetSocketAddress(
  InetAddress.getByName(hostname),
  port
);
sock.connect(address, SOCKET_TIMEOUT);
sock.setSoTimeout(SOCKET_TIMEOUT);
reader = new ReaderGuacamoleReader(new InputStreamReader(sock.getInputStream(),   "UTF-8"));
writer = new WriterGuacamoleWriter(new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
origin: nutzam/nutz

public TcpConnector connect() {
  if (isClosed()) {
    log.infof("Connect socket <-> %s:%d", host, port);
    try {
      socket = new Socket(InetAddress.getByName(host), port);
      socket.setTcpNoDelay(true);
      reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      writer = new OutputStreamWriter(socket.getOutputStream());
    }
    catch (UnknownHostException e) {
      log.warnf("Unknown host '%s:%d'", host, port);
      throw Lang.wrapThrow(e);
    }
    catch (IOException e) {
      log.warnf("IOError '%s:%d'", host, port);
      throw Lang.wrapThrow(e);
    }
  }
  return this;
}
origin: Qihoo360/XLearning

LOG.info("Setting environments for the MXNet scheduler");
dmlcPsRootUri = applicationMasterHostname;
Socket schedulerReservedSocket = new Socket();
try {
 Utilities.getReservePort(schedulerReservedSocket, InetAddress.getByName(applicationMasterHostname).getHostAddress(), reservePortBegin, reservePortEnd);
} catch (IOException e) {
 LOG.error("Can not get available port");
dmlcPsRootPort = schedulerReservedSocket.getLocalPort();
List<String> schedulerEnv = new ArrayList<>(20);
Map<String, String> userEnv = new HashMap<>();
 Utilities.getReservePort(schedulerReservedSocket, InetAddress.getByName(applicationMasterHostname).getHostAddress(), reservePortBegin, reservePortEnd);
} catch (IOException e) {
 LOG.error("Can not get available port");
InetAddress address = null;
try {
 address = InetAddress.getByName(applicationMasterHostname);
 dmlcPsRootUri = address.getHostAddress();
} catch (UnknownHostException e) {
 LOG.info("acquire host ip failed " + e);
 Utilities.getReservePort(schedulerReservedSocket, InetAddress.getByName(applicationMasterHostname).getHostAddress(), reservePortBegin, reservePortEnd);
} catch (IOException e) {
 LOG.error("Can not get available port");
origin: apache/flink

private Inet6Address getLocalIPv6Address() {
  try {
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
      NetworkInterface netInterface = e.nextElement();
      Enumeration<InetAddress> ee = netInterface.getInetAddresses();
      while (ee.hasMoreElements()) {
        InetAddress addr = ee.nextElement();
        if (addr instanceof Inet6Address && (!addr.isLoopbackAddress()) && (!addr.isAnyLocalAddress())) {
          InetSocketAddress socketAddress = new InetSocketAddress(addr, 0);
            ServerSocket sock = new ServerSocket();
            sock.bind(socketAddress);
            sock.close();
            ActorSystem as = AkkaUtils.createActorSystem(
                new Configuration(),
                new Some<scala.Tuple2<String, Object>>(new scala.Tuple2<String, Object>(addr.getHostAddress(), port)));
            as.shutdown();
origin: MovingBlocks/Terasology

bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
Channel listenChannel = bootstrap.bind(new InetSocketAddress(port));
allChannels.add(listenChannel);
logger.info("Started server on port {}", port);
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
  NetworkInterface ifc = interfaces.nextElement();
  if (!ifc.isLoopback()) {
    for (InterfaceAddress ifadr : ifc.getInterfaceAddresses()) {
      InetAddress adr = ifadr.getAddress();
      logger.info("Listening on network interface \"{}\", hostname \"{}\" ({})",
          ifc.getDisplayName(), adr.getCanonicalHostName(), adr.getHostAddress());
origin: eclipse-vertx/vert.x

private String getDefaultAddress() {
 Enumeration<NetworkInterface> nets;
 try {
  nets = NetworkInterface.getNetworkInterfaces();
 } catch (SocketException e) {
  return null;
 }
 NetworkInterface netinf;
 while (nets.hasMoreElements()) {
  netinf = nets.nextElement();
  Enumeration<InetAddress> addresses = netinf.getInetAddresses();
  while (addresses.hasMoreElements()) {
   InetAddress address = addresses.nextElement();
   if (!address.isAnyLocalAddress() && !address.isMulticastAddress()
    && !(address instanceof Inet6Address)) {
    return address.getHostAddress();
   }
  }
 }
 return null;
}
origin: Qihoo360/XLearning

 LOG.info("Reserved available port: " + reservedSocket.getLocalPort());
 this.lightLDALocalPort = reservedSocket.getLocalPort();
 InetAddress address = null;
 try {
  address = InetAddress.getByName(envs.get(ApplicationConstants.Environment.NM_HOST.toString()));
 } catch (UnknownHostException e) {
  LOG.info("acquire host ip failed " + e);
  reportFailedAndExit();
 String ipPortStr = this.index + " " + address.getHostAddress() + ":" + this.lightLDALocalPort;
 this.lightLDAEndpoint = address.getHostAddress() + ":" + this.lightLDALocalPort;
 LOG.info("lightLDA ip port string is: " + ipPortStr);
 amClient.reportLightLDAIpPort(containerId, ipPortStr);
InetAddress address = null;
try {
 address = InetAddress.getByName(envs.get(ApplicationConstants.Environment.NM_HOST.toString()));
} catch (UnknownHostException e) {
 LOG.info("acquire host ip failed " + e);
 reportFailedAndExit();
String ipPortStr = address.getHostAddress() + " " + reservedSocket.getLocalPort();
LOG.info("lightGBM ip port string is: " + ipPortStr);
amClient.reportLightGbmIpPort(containerId, ipPortStr);
 Utilities.getReservePort(boardReservedSocket, InetAddress.getByName(localHost).getHostAddress(), reservePortBegin, reservePortEnd);
} catch (IOException e) {
 LOG.error("Can not get available port");
origin: apache/incubator-dubbo

private static InetAddress getLocalAddress0() {
  InetAddress localAddress = null;
  try {
    localAddress = InetAddress.getLocalHost();
    Optional<InetAddress> addressOp = toValidAddress(localAddress);
    if (addressOp.isPresent()) {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    if (null == interfaces) {
      return localAddress;
    while (interfaces.hasMoreElements()) {
      try {
        NetworkInterface network = interfaces.nextElement();
        Enumeration<InetAddress> addresses = network.getInetAddresses();
        while (addresses.hasMoreElements()) {
          try {
            Optional<InetAddress> addressOp = toValidAddress(addresses.nextElement());
java.netInetAddress

Javadoc

An Internet Protocol (IP) address. This can be either an IPv4 address or an IPv6 address, and in practice you'll have an instance of either Inet4Address or Inet6Address (this class cannot be instantiated directly). Most code does not need to distinguish between the two families, and should use InetAddress.

An InetAddress may have a hostname (accessible via getHostName), but may not, depending on how the InetAddress was created.

IPv4 numeric address formats

The getAllByName method accepts IPv4 addresses in the "decimal-dotted-quad" form only:

  • "1.2.3.4" - 1.2.3.4

IPv6 numeric address formats

The getAllByName method accepts IPv6 addresses in the following forms (this text comes from RFC 2373, which you should consult for full details of IPv6 addressing):

  • The preferred form is x:x:x:x:x:x:x:x, where the 'x's are the hexadecimal values of the eight 16-bit pieces of the address. Note that it is not necessary to write the leading zeros in an individual field, but there must be at least one numeral in every field (except for the case described in the next bullet). Examples:

     
    FEDC:BA98:7654:3210:FEDC:BA98:7654:3210 
    1080:0:0:0:8:800:200C:417A

  • Due to some methods of allocating certain styles of IPv6 addresses, it will be common for addresses to contain long strings of zero bits. In order to make writing addresses containing zero bits easier a special syntax is available to compress the zeros. The use of "::" indicates multiple groups of 16-bits of zeros. The "::" can only appear once in an address. The "::" can also be used to compress the leading and/or trailing zeros in an address. For example the following addresses:
     
    1080:0:0:0:8:800:200C:417A  a unicast address 
    FF01:0:0:0:0:0:0:101        a multicast address 
    0:0:0:0:0:0:0:1             the loopback address 
    0:0:0:0:0:0:0:0             the unspecified addresses
    may be represented as:
     
    1080::8:800:200C:417A       a unicast address 
    FF01::101                   a multicast address 
    ::1                         the loopback address 
    ::                          the unspecified addresses
  • An alternative form that is sometimes more convenient when dealing with a mixed environment of IPv4 and IPv6 nodes is x:x:x:x:x:x:d.d.d.d, where the 'x's are the hexadecimal values of the six high-order 16-bit pieces of the address, and the 'd's are the decimal values of the four low-order 8-bit pieces of the address (standard IPv4 representation). Examples:

     
    0:0:0:0:0:0:13.1.68.3 
    0:0:0:0:0:FFFF:129.144.52.38
    or in compressed form:
     
    ::13.1.68.3 
    ::FFFF:129.144.52.38

Scopes are given using a trailing % followed by the scope id, as in 1080::8:800:200C:417A%2 or 1080::8:800:200C:417A%en0. See RFC 4007 for more on IPv6's scoped address architecture.

Additionally, for backwards compatibility, IPv6 addresses may be surrounded by square brackets.

DNS caching

In Android 4.0 (Ice Cream Sandwich) and earlier, DNS caching was performed both by InetAddress and by the C library, which meant that DNS TTLs could not be honored correctly. In later releases, caching is done solely by the C library and DNS TTLs are honored.

Most used methods

  • getHostAddress
    Returns the IP address string in textual presentation.
  • getByName
  • getLocalHost
  • getHostName
  • getAddress
    Returns the raw IP address of this InetAddress object. The result is in network byte order: the high
  • isLoopbackAddress
    Utility routine to check if the InetAddress is a loopback address.
  • getCanonicalHostName
    Gets the fully qualified domain name for this IP address. Best effort method, meaning we may not be
  • getByAddress
  • equals
    Compares this object against the specified object. The result is true if and only if the argument is
  • toString
    Converts this IP address to a String. The string returned is of the form: hostname / literal IP addr
  • getAllByName
  • isAnyLocalAddress
    Utility routine to check if the InetAddress in a wildcard address.
  • getAllByName,
  • isAnyLocalAddress,
  • isSiteLocalAddress,
  • getLoopbackAddress,
  • isLinkLocalAddress,
  • hashCode,
  • isMulticastAddress,
  • isReachable,
  • badAddressLength,
  • isNumeric

Popular in Java

  • Finding current android device location
  • getSystemService (Context)
  • scheduleAtFixedRate (ScheduledExecutorService)
  • onRequestPermissionsResult (Fragment)
  • Thread (java.lang)
    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to ha
  • Stack (java.util)
    Stack is a Last-In/First-Out(LIFO) data structure which represents a stack of objects. It enables u
  • TimerTask (java.util)
    The TimerTask class represents a task to run at a specified time. The task may be run once or repeat
  • ThreadPoolExecutor (java.util.concurrent)
    An ExecutorService that executes each submitted task using one of possibly several pooled threads, n
  • HttpServletRequest (javax.servlet.http)
    Extends the javax.servlet.ServletRequest interface to provide request information for HTTP servlets.
  • Option (scala)
  • Top PhpStorm plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now