Showing posts with label java - net functions. Show all posts
Showing posts with label java - net functions. Show all posts

Friday, March 2, 2018

JAVA - How check if client is reachable - ping to client

String sText = "";
try {

  /* prepare IP address */
      
  String ipAddress = "10.26.1.3";
  InetAddress inet = InetAddress.getByName( ipAddress );

  /* check ping (timeout=1000 ms) */

  if ( inet.isReachable( 1000 ) ) 
    sText = "Client is reachable";
  else
    sText = "Client isn`t reachable";     
      
} catch( UnknownHostException ex ) {
  Logger.getLogger( FXMLMainController.class.getName() ).log( Level.SEVERE, null, ex );
} catch( IOException ex ) {
  Logger.getLogger( FXMLMainController.class.getName() ).log( Level.SEVERE, null, ex );
}
    
memo.setText( sText );    

Thursday, February 8, 2018

JAVA - How to get local IP address and host name

import java.net.InetAddress;
import java.net.UnknownHostException;
...
try {
  InetAddress ia = InetAddress.getLocalHost();

  /* -- write results */

  System.out.println( ia.getHostAddress() );
  System.out.println( ia.getHostName() );

  System.out.println( ia.toString() );

  System.out.println( ia.getCanonicalHostName() );

  for ( int i = 0; i < ia.getAddress().length; i++ )
    System.out.println( ia.getAddress()[i] );

} catch ( UnknownHostException ex ) {
}
Output (could be):
10.26.1.11
pc082
pc082/10.26.1.11
pc082.org.local
10
26
1
11

Friday, December 22, 2017

JAVA - How download document from web

This example is used for downloading rss channel:
try {    
  /* - open source */
      
  URL website = new URL( app.pSetup.getData().sRSSLink );
  InputStream in = website.openStream();      
  ...
}
catch( MalformedURLException ex ) {
  Logger.getLogger( FXMLMainController.class.getName() ).log( Level.SEVERE, null, ex );
  return false;
} 
catch( IOException ex ) {
  Logger.getLogger( FXMLMainController.class.getName() ).log( Level.SEVERE, null, ex );
  return false;
}

Friday, December 8, 2017

JAVA - How to get device MAC address

For getting MAC address of the device use this code:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.net.SocketException;
...
try {
  InetAddress ia = InetAddress.getLocalHost();

  NetworkInterface ni = NetworkInterface.getByInetAddress( ia );

  /* -- write results */

  System.out.println( ni.getName() );
  System.out.println( ni.getDisplayName() );

  byte[] mac = ni.getHardwareAddress();

  for ( int i = 0; i < mac.length; i++ )
    System.out.format( "%02X%s",  mac[i], ( i < mac.length - 1 ) ? "-" : "" );

  } 
  catch ( UnknownHostException ex ) {} 
  catch ( SocketException ex ) {}
...
Output:
Realtek PCIe GBE Family Controller - Packet Scheduler Miniport
eth2
70-71-BC-54-E7-8B