Showing posts with label Java networking. Show all posts
Showing posts with label Java networking. Show all posts

Tuesday, 3 May 2016

How do I get MAC address of a host ?


Use getHardwareAddress() method from java.net.NetworkInterface class.

Code
try {
  InetAddress address = InetAddress.getLocalHost();
  //InetAddress address = InetAddress.getByName("www.google.co.in");
   
  System.out.println("Current IP address: " + 
                       address.getHostAddress());

  NetworkInterface network = 
       NetworkInterface.getByInetAddress(address);

  byte[] mac = network.getHardwareAddress();

  System.out.print("Current MAC address : ");

  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < mac.length; i++) {
      sb.append(
         String.format("%02X%s", mac[i], (i<mac.length-1)?"-":"")
      );
  }

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

} catch (UnknownHostException e) {
  ...
} catch (SocketException e){

  ...
}

Sunday, 24 April 2016

Socket vs. Port


A socket is an end point of a bidirectional communication.
a port is a logical data connection that can be used to exchange data without the use of a temporary file or storage.


Association between Socket and Port
A socket is associated with a port and there can be multiple sockets associated with a port.

There can be a single passive socket associated with a port that is waiting for incoming connections.
There can be multiple active sockets that correspond to connections that are open in that port.

How to send a HTTP GET request ?


Send a HTTP GET request

Example
String requestUrl = "http: //www.google.be";
try {
    URL url = new URL(requestUrl);
    BufferedReader in = 
        new BufferedReader(new InputStreamReader(url.openStream()));

    String inputLine;
    System.out.println("-----RESPONSE START-----");
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }

    in.close();
    System.out.println("-----RESPONSE END-----");
 } catch (IOException e) {
    e.printStackTrace();

 }

How to send a POST request ?


Example
try {
   // Construct data
   String data = URLEncoder.encode("key1", "UTF-8") + "=" 
                  + URLEncoder.encode("value1", "UTF-8");

   data += "&" + URLEncoder.encode("key2", "UTF-8") + "="
                  + URLEncoder.encode("value2", "UTF-8");

   // Send data
   URL url = new URL("http://hostname:80/cgi");
   URLConnection conn = url.openConnection();
   conn.setDoOutput(true);
   OutputStreamWriter wr = 
                new OutputStreamWriter(conn.getOutputStream());
   wr.write(data);
   wr.flush();

   // Get the response
   BufferedReader rd = 
      new BufferedReader(new InputStreamReader(conn.getInputStream()));
   String line;
   while ((line = rd.readLine()) != null) {
     // Process line...
   }

   wr.close();
   rd.close();
} catch (Exception e) {
   e.printStackTrace();

}

How to open a website or local site in browser using Java code ?


Opening a website or local site using Java code

Example
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();

try {
   java.net.URI uri = new java.net.URI("http://www.google.com");
   // Open browser with website URL
   desktop.browse(uri);

   File localFile = new File("C:\\shaan\\localsite\\home.html");
   // Open browser with local HTML page
   desktop.open(localFile);
} catch (URISyntaxException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();

}

ServerSocket vs. DatagramSocket


DatagramSocket allows a server to accept UDP packets, whereas 
ServerSocket allows an application to accept TCP connections.

UDP packets don't guarantee delivery, you'll need to handle missing packets in your client/server.

TCP guarantees delivery, so all you need to do is have your applications read and write using a socket's InputStream and OutputStream.

How can I find out who is accessing my server ?


If you're using a DatagramSocket, every packet that you receive will contain the address and port from which it was sent.

Example
DatagramPacket packet = null;
// Receive next packet
myDatagramSocket.receive(packet);
// Print address + port
System.out.println ("Packet from : " + 
     packet.getAddress().getHostAddress() + ':' + packet.getPort());

If you're using a ServerSocket, then every socket connection you accept will contain similar information.

Example
Socket mySock = myServerSocket.accept();
// Print address + port

System.out.println ("Connection from : " + mySock.getInetAddress().getHostAddress() + ':' + mySock.getPort());

How do I handle timeouts in my networking applications ?


You can use socket options to generate a timeout after a read operation blocks for a specified length of time.

java.net.Socket.setSoTimeout() 
This method allows you to specify the maximum amount of time a Socket I/O operation will block before throwing an InterruptedIOException.
This allows you to trap read timeouts, and handle them correctly.

How do I get the IP address and hostname of a machine ?


Get the IP address of a machine from its hostname
The InetAddress class is able to resolve IP addresses for you.
Call getHostAddress() method of InetAddress, which returns a string in the xxx.xxx.xxx.xxx address form.

InetAddress inet = 
             InetAddress.getByName("http://www.davidreilly.com");

System.out.println ("IP: " + inet.getHostAddress());


Find out the current IP address for my machine
The InetAddress has a static method called getLocalHost() which will return the current address of the local machine.
You can then use the getHostAddress() method to get the IP address.

InetAddress local = InetAddress.getLocalHost();

System.out.println ("Local IP: " + local.getHostAddress());


Get the hostname of a machine from its IP address
The InetAddress class contains a method that can return the domain name of an IP address.
You need to obtain an InetAddress class, and then call its getHostName() method.
This will return the hostname for that IP address.
Depending on the platform, a partial or a fully qualified hostname may be returned.

InetAddress inet = InetAddress.getByName("209.204.220.121");

System.out.println ("Host: " + inet.getHostName());

TCP vs. UDP protocol


TCP and UDP are both transport-level protocols.

TCP is designed to provide reliable communication across a variety of reliable and unreliable networks and internets.

UDP provides a connectionless service for application-level procedures.

Thus, UDP is basically an unreliable service
Delivery and duplicate protection are not guaranteed.

When my client connects to my server, why does no data come out ?


Step 1. Check server
Try and isolate the cause of the problem, by checking whether the server is responding correctly.
If you're writing a TCP service, then you can telnet to the port the server uses, and check to see if it is responding to data.
If so, then the fault is more than likely in the client, and if not, you' ve found your problem.

Step 2. Use Debugger
A debugger can be very helpful in tracking down the precise location of server errors.
If your fault looks like it is in the client, then it can often be caused by buffered I/O.

If you're using a buffered stream, or a writer (such as PrintWriter), you may need to manually flush the data. Otherwise, it will be queued up but not sent, causing both client and server to stall.
The problem can even be intermittent, as the buffer will flush sometimes (when it becomes full) but not other times.

Saturday, 23 April 2016

What are the advantages and disadvantages of Socket ?


The combination of an IP address and a port number is called a socket.

Advantages of Java Sockets
  • Sockets are flexible and sufficient.
  • Efficient socket based programming can be easily implemented for general communications.
  • Sockets cause low network traffic.
  • Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information. 

Disadvantages of Java Sockets
  • Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network.
  • Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
  • Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.