Socket & Networking Programming


ARP :

    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    
    public class MacAddress {
            public static void main(String[] args){
                        try{                 
    Scanner console = new Scanner(System.in);
    System.out.println("Enter System Name: ");
    String ipaddr = console.nextLine();
    InetAddress address = InetAddress.getByName(ipaddr);
    System.out.println("address = "+address);
    NetworkInterface ni = NetworkInterface.getByInetAddress(address);
   
    if (ni!=null){
            byte[] mac = ni.getHardwareAddress();
            if (mac!= null){
            System.out.print("MAC Address : ");
            for (int i=0; i<mac.length; i++){
            System.out.format("%02X%s", mac[i], (i<mac.length - 1) ? "-" :"");
            }
    }
    else{
            System.out.println("Address doesn't exist or is not accessible/");
            }
    } 
else{
            System.out.println("Network Interface for the specified address is not found");
            }
  }
  catch(Exception e){   }
  }
}

OUTPUT:





UDP Chat Application
MyClient.java  :
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{     
Socket s=new Socket("localhost",6666);      
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}







MyServer.java :
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String  str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}