Showing posts with label Networking-Java. Show all posts
Showing posts with label Networking-Java. Show all posts

Thursday, October 15, 2009

Java Source Code to find the IP Address of the machine

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class ipfind {

ipfind(){

try{
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements()){
NetworkInterface ni = (NetworkInterface)e.nextElement();
Enumeration e1 = ni.getInetAddresses();
while(e1.hasMoreElements()){
InetAddress inetAddress = (InetAddress)e1.nextElement();
System.out.println(" " + inetAddress.getHostAddress());
}

}
}catch(Exception e){

}
}

public static void main(String args[]){
ipfind ipf = new ipfind();
}
}

Tuesday, October 6, 2009

Java Source Code to access the Active Directory Server

Active Directory:
Active Directory is a directory structure created by Microsoft that provides a variety of network services, including LDAP-like directory services.

An active directory (sometimes referred to as an AD) does a variety of functions including the ability to provide information on objects, helps organize these objects for easy retrieval and access, allows access by end users and administrators and allows the administrator to set security up for the directory.

An active directory can be defined as a hierarchical structure and this structure is usually broken up into three main categories, the resources which might include hardware such as printers, services for end users such as web email servers and objects which are the main
functions of the domain and network.
LDAP:
LDAP (Lightweight Directory Access Protocol) is a protocol for communications between LDAP servers and LDAP clients. LDAP servers store "directories" which are access by LDAP clients.

LDAP is called lightweight because it is a smaller and easier protocol which was derived from the X.500 DAP (Directory Access Protocol) defined in the OSI network protocol stack.

LDAP servers store a hierarchical directory of information. In LDAP parlance, a fully-qualified name for a directory entry is called a Distinguished Name. Unlike DNS (Domain Name Service) FQDN's (Fully Qualified Domain Names), LDAP DN's store the most significant data to the right.

[Source: Internet]
The Java source code which I am going to write will connect to the Active Directory Server of web email server configured in the Microsoft Exchange Outlook.

Before going into the code, below are the steps which might reveal the LDAP server name in the MS outlook client.









Click on the properties
The RED colored portion would be our LDAP server name





Below is the code to connect to LDAP server.

ActiveDirectoryDemo.java

import java.util.Hashtable;
import javax.naming.ldap.*;
import javax.naming.directory.*;
import javax.naming.*;

public class ActiveDirectoryDemo {
public static void main(String[] args) {
Hashtable env = new Hashtable();
env.put(Context.SECURITY_PRINCIPAL,"CN=username,OU=companynameOU,DC=company name.com");//User
env.put(Context.SECURITY_CREDENTIALS, "password");//Password
env.put(Context.REFERRAL, "follow");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://servername.Company name.com:port number = 389");
env.put(Context.SECURITY_AUTHENTICATION,"none");
try {
LdapContext context = new InitialLdapContext(env, null);
String base = "";
String filter = "(objectclass=*)";
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.OBJECT_SCOPE);
NamingEnumeration answer = context.search(base, filter, controls);

// ... process attributes ...
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult)answer.next();
System.out.println("RootDSE: " + sr.getName());

Attributes attrs = sr.getAttributes();
if (attrs != null) {
try {
System.out.println("Naming Context: " + attrs.get("defaultNamingContext").get());
System.out.println("Schema Context: " + attrs.get("schemaNamingContext").get());
System.out.println("DNS: " + attrs.get("dnsHostName").get());
System.out.println("Server Name: " + attrs.get("serverName").get());
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
catch (NamingException e) {
e.printStackTrace();
}
}
}


Output:


Monday, June 15, 2009

Wake on LAN using Java

Wake on LAN (WoL) is a standard that allows a computer to be turned on remotely by a message sent through the network.


It is platform independent technology that sends Magic Packet (containing its MAC address) to wake up computers.


When the listening computer receives this packet, the network card checks the packet for the correct information. If the Magic Packet is valid, the network card takes the computer out of hibernation or standby, or starts it up (Source: wiki).


In order for Wake on LAN to work, parts of the network interface need to stay on.


This consumes a standby power, small compared to the computer's normal operating power. If Wake on LAN is not needed, disabling it may reduce power consumption while the computer is switched off but still plugged in.
[Source: wiki]


To send magic packets in command prompt wolcmd command is used.


This is the java code to send Magic Packets to a machine provided its IP address and MAC address are available (compatible with java 1.6).



import java.io.*;
import java.net.*;

public class WakeOnLan {

public static final int PORT = 9;

public static void main(String[] args) {

String ipStr = "<>";
String macStr = "<>";
try {
byte[] macBytes = getMacBytes(macStr);
byte[] bytes = new byte[6 + 16 * macBytes.length];
for (int i = 0; i < 6; i++) {
bytes[i] = (byte) 0xff;
}
for (int i = 6; i < bytes.length; i += macBytes.length) {
System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
}

InetAddress address = InetAddress.getByName(ipStr);
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();

System.out.println("Wake-on-LAN packet sent.");
}
catch (Exception e) {
System.out.println("Failed to send Wake-on-LAN packet:" + e);
System.exit(1);
}

}

private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
byte[] bytes = new byte[6];
String[] hex = macStr.split("(\\:\\-)");
if (hex.length != 6) {
throw new IllegalArgumentException("Invalid MAC address.");
}
try {
for (int i = 0; i < 6; i++) {
bytes[i] = (byte) Integer.parseInt(hex[i], 16);
}
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid hex digit in MAC address.");
}
return bytes;
}
}

Finding MAC Address using Java

MAC Address stands for Media Access Control Address. It is a unique identifier to most network interface cards (LAN Card) by the manufacturer for identification. The MAC which is also known as a physical address or adapter address usually encodes the registered identification number of the manufacturer.


You can always find the MAC address of the computer by going to command prompt and type: ipconfig /all. The physical address of the machine is printed like the below format: 08-00-27-DC-4A-9E.


Here I am going to put the code to find out MAC address of a machine using JAVA.
We will do it using getHardwareAddress() method of NetworkInterface class of java.net package. The method has been introduced in the JDK 1.6. So the below program is compatible with JDK 1.6.

import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {

public static void main(String[] args) {
try {

InetAddress address = InetAddress.getLocalHost();
System.out.println("Address "+address);
/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
System.out.println("NI = "+ni);
byte[] mac = ni.getHardwareAddress();


/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/

System.out.println("MAC Address is ");
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
}
}

Total Pageviews