Search This Blog

How to Find Other Computers in Your Network - Java Application Programming

When you are developing some application software, you may have to search other computers or mobiles (android) in the network. Think about chatting application scenario in which the application shows the list of available computers (with the same chatting application). We will see in this post:

  • how to identify other computers in the network (with same application running)
  • how to get the IP address of those computers
  • how to tell other computers in the network, "I am here".

It is simple. We do it this way; (i) Each computer (or mobile) shouts that it is in the network (ii) Others listen to this. We make use of multicasting for this purpose. Multicasing is same as sending UDP datagrams. But still there are some minor differences. In java, we use MulticastSocket instead DatagramSocket. MulticastSocket has additional facilities to join or leave multicast groups. MulticastSocket class helps for sending and receiving IP multicast packets. In multicasting, we send DatagramPackets to one of the multicast addresses. The multicast addresses are class D IP addresses ranging from 224.0.0.0 (exclusive) to 239.255.255.255 (inclusive). A multicast group is determined by a multicast ip address and a port number. Any computer can send packets to a multicast group. But to receive packets in a multicast group, you should join that group. Really, we can't call this a broadcast. Broadcast is the term used to describe communication where packet(s) are sent from one or more devices to all other devices in the network. Multicast means sending packets from one or more devices to a set of other devices determined by a logical group (not all others).

For example, consider a group 239.0.0.73:19360. Suppose, we have chat servers and chat clients. Chat clients search for chat servers to join a chat. So the chat servers should send UDP packets (Datagram Packets) to 239.0.0.73:19360, no matter on which port the server has opened the multicast socket. But, for the receivers (clients in this example), should open multicast sockets with port number 19360 and join multicast group 239.0.0.73 to receive datagrams sent to multicast group 239.0.0.73:19360. In the following java code, we will see how to do this.

Sender

The following is the java code used by the multicast message sender (chat server in this example).

try{
MulticastSocket mcs=new MulticastSocket(); //creating multicast socket
//port number is assigned by the OS
mcs.setTimeToLive(5);
String decl="!!Chatting%%"+System.getProperty("user.name")+"^^";//broadcast message
DatagramPacket pkt=new DatagramPacket(decl.getBytes(),decl.length(),InetAddress.getByName("239.0.0.73"),19360);//multicast packet

        Socket s=null; //TCP socket for chatting
        ServerSocket ss=new ServerSocket(9999);
//TCP Serversocket to accept connection request from client
        ss.setSoTimeout(500);
        boolean connected=false;
        do{
            try{
            mcs.send(pkt);
            System.out.println("sending: "+decl);
            s=ss.accept();
            connected=true;
            System.out.println("connected to"+s);
            }catch(SocketTimeoutException eee){}
          }while(connected==false);
}catch(Exception ex){ex.printStackTrace();}

Program explanation

line 1: The sender creates a MulticastSocket at random port. The port number is assigned by OS. Port number doesn't matter since sender only needs to send packet to the multicast group, and don't want to receive from.

line 3: Sets time to live (TTL) for the multicast packets.It is the maximum number routers the packets can go through. This value is decremented at every router on the route to its destination. If the TTL field reaches zero before the datagram arrives at its destination, the packet will be dropped. If there are 10 routers between the sender and the receiver, the TTL value should be at least 10 for the packet to reach its destination.

line 4: The content of packet. Here we use !!Chatting string determine whether it is our chatting application sending this packet. We also sends the username of the sender.

line 5: Creating the datagram packet with the message. destination ip and port are set to our multicast group's ip and port.

line 7,8: We use the socket and ServerSocket for TCP chat communication later. This depends on your goal.

line 14: Sending the multicast datagram packet.

Receiver

The following is the java code to receive multicast messages (datagram packets).

try{
        MulticastSocket mcs=new MulticastSocket(19360);
        mcs.joinGroup(InetAddress.getByName("239.0.0.73"));
        byte[] bu=new byte[100];
        DatagramPacket dp=new DatagramPacket(bu,100);
        mcs.receive(dp);
        InetAddress ip=dp.getAddress();
        String sss=new String(dp.getData());
        System.out.println("Server found:"+sss.substring(sss.indexOf("%%")+2,sss.indexOf("^^")));
        s=new Socket(ip,9999);
   }catch(Exception ex){ex.printStackTrace();}

Program explanation

line 2: The client creates a MulticastSocket at port number 19360. It is the port number of our multicast group.
line 3: Joined the group using the ip 239.0.0.73.
line 6: Receiving packet.
line 7: Retrieving IP address of sender (server).
line 8: Retrieving message from datagram packet.
line 9: Extracting server users name from message
line 10: Establishing TCP connection with server using the retrieved IP

Java Program to Display a String in Reverse Order Without Using Loop or Another Array

In this post, we will see a java program to reverse a string without using any loops or temporary array. Such programming questions are often asked in interviews. It is so simple. We make use of recursion to store the string temporarily. Actually, we do not use any loop. We can easily do it without using any loops. Nor we need to declare an extra array. But when we make use of recursion, stack is used internally for calling each instance of the recursive method. Remember, we should not use the reverse method in StringBuilder class or StringBuffer class. The following java program displays the string in reverse order.


import java.util.Scanner;

public class StrRev{
static int len;
static String str;

static void recurse(int i)
{
    if(i<len-1)
        recurse(i+1);
    System.out.print(str.charAt(i));
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine();
    len=str.length();
    recurse(0);
    }
}

In the above java program we just displayed the string in reverse order. we did not reverse the string in memory. In the following java program, we will see how to rearrange the string in reverse order without using any loops or extra arrays.

import java.util.Scanner;

public class StrRev{
static int len;
static char[] str;

static void recurse(int i)
{
    char a=str[i];
    if(i<len-1)
        recurse(i+1);
    str[len-i-1]=a;
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine().toCharArray();
    len=str.length;
    recurse(0);
    System.out.println(String.copyValueOf(str));
    }
}

In the above java program, we stored the input string initially as a character array. Using a recursive method, we rearranged the character array in reverse order. Then we displayed the character array as a string

Java Program to Find Minimum of Two Numbers

Java Program to compare three numbers and display the minimum of two numbers. Here, we will see a simple java program to display the smaller number among two input numbers. This program takes first input as the number of sets of numbers (a set contains two numbers whose minimum is to be displayed). Then it takes numbers as sets of 2 numbers. For every pair of numbers, the java program displays the smaller number. The following java program does it. It makes use of the ternary operator (conditional operator) and Scanner class in java.


import java.util.Scanner;

public class MinofTwo {

public static void main(String[] arg)   
    {
    Scanner sc = new Scanner(System.in);
    int n=sc.nextInt(),a,b;
    while(n>0)
        {
        System.out.println((a=sc.nextInt())<(b=sc.nextInt())?a:b);
        n--;
        }
    }
}

Java Program to Find Minimum of Three

It is the basics of any programming language to compare three numbers and display the minimum of the three. Here, we will see a short java program to display the smallest number among three input numbers. This program takes first input as the number of sets of numbers (a set contains three numbers whose minimum is to be displayed). Then it takes numbers as sets of three numbers. for every three number, the java program displays the smallest of them. The following program does it. It makes use of the ternary operator (conditional operator) and Scanner class.

import java.util.Scanner;

public class MinOfThree {
public static void main(String[] arg)
 
    {
    Scanner sc = new Scanner(System.in);
    int n=sc.nextInt(),a,b,c;
    while(n>0)
        {
        if((a=sc.nextInt())>(b=sc.nextInt()))
            System.out.println(b<(c=sc.nextInt())?b:c);
        else
            System.out.println(a<(c=sc.nextInt())?a:c);
        n--;
        }
    }
}


Java Program to Reverse a String

Here, we will see a java program to reverse a string. The string is read and is displayed in reverse order. Java program to display an input string in reverse order.


import java.util.Scanner;

public class BMI {
public static void main(String[] arg)
    {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string");
    String s=sc.nextLine();
    for(int i=s.length()-1;i>=0;i--)
            System.out.print(s.charAt(i));
    }
}

Java Program to Find Sum of First N Terms of an Arithmetic Progression

In this post we will see a java program to calculate sum of first n terms of an arithmetic progression. Arithmetic progression is also called AP (short for Arithmetic progression). The equation to find sum of first n terms of an arithmetic progression is as follows:

sum of first n terms = (n / 2) * (2 * a + (n - 1) * d)
sum of first n terms of an arithmetic progression, equation to find sum of an ap,
Sum of first n terms of an AP (arithmetic progression)

Now, we will see a java program to find sum of first n terms of an AP. The java program is as follows:


import java.util.Scanner;

public class SumofAP {
public static void main(String[] arg)
    {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first term, common difference and n (number of terms)");
    int a=sc.nextInt(),d=sc.nextInt(),n=sc.nextInt();
    System.out.print("Sum: "+n*(2*a+(n-1)*d)/2);
    }
}


Java Program to Display First N Terms of an Arithmetic Progression

This post contains java program to display first n terms of an AP (arithmetic progression). Generally the following equation to find nth term of arithmetic progression is used.

nth term of AP = a + (n - 1) * d

where a is first term and d is common difference. Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on adding the common difference. We need not to use the above equation each time. The java program to display first n terms of a arithmetic progression (AP) is as follows:
public class APTerms {
public static void main(String[] arg)
    {
    int a,d,n;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first term, common difference and n (number of terms)");
    a=sc.nextInt()-(d=sc.nextInt());
    n=sc.nextInt();
    for(int i=0;i<n;i++)
        System.out.print(" "+(a+=d));
    }
}

Java Program to Display First N Terms of Geometric Progression

This post contains java program to display first n terms of a GP (geometric progression). Generally the following equation to find nth term of geometric progression is used.

Nth term of GP =  a * r(n-1)
Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on multiplying with the common ratio. We need not to use the above equation each time. The java program to display first n terms of a geometric progression (GP) is as follows:

import java.util.Scanner;

public class GPTerms {
public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter first term, common ratio and n (number of terms)");
    int a=sc.nextInt(),r=sc.nextInt(),n=sc.nextInt();
    System.out.print("\n"+a);
    for(int i=1;i<n;i++)
        System.out.print(" "+(a*=r));
    }
}

Java Program to Find Sum of First N Terms of Geometric Progression

In this post we will see a java program to calculate sum of first n terms of a geometric progression. Geometric progression is also called GP (short for Geometric progression). The equation to find sum of first n terms of a geometric progression is as follows:

sum= a*(1-r^n)/(1-r)
sum of geometric progression, sum of gp, gp sum
sum of first n terms of geometric progression

Now, we will see a java program to find sum of first n terms of a GP. There is a case in which the above equation fails. When r (common ratio) is 1, the above equation won't work. Then every term in the GP will be same as first term. Therefore, in that case, the sum is a*n. The program is as follows:



import java.util.Scanner;

public class SumGP {
public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter first term, common ratio and n (number of terms)");
    int a=sc.nextInt(),r=sc.nextInt(),n=sc.nextInt();
        System.out.println((r==1)?"Sum is:"+a*n:"Sum is:"+(float)a*(1-Math.pow(r,n))/(1-r));
    }
}

Java Program to Check Whether It Is Possible to Draw a Triangle with Given Sides

For existence of a triangle there is a condition. The condition is that the sum of the lengths of any two sides of a triangle must be greater than or equal to the length of the third side. If the sum of the lengths of any two sides of a triangle is equal to the length of the third side, it forms a triangle with zero area. The vertices are collinear in that case. Still we can say that the triangle exists. So, here we will see a java program to check whether a triangle exists or not with given sides. The program is as follows:

import java.util.Scanner;

public class TriangleSide {
public static void main(String[] arg)
    {
    
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the sides of triangle");
    int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt();
    if(a+b>=c&&b+c>=a&&c+a>=b)
        System.out.println("possible");
    else
        System.out.println("impossible");
    }
}