Pemrograman Jejaring Komputer: Pertemuan 6 Oleh: Herman, Skom., MM
Pemrograman Jejaring Komputer: Pertemuan 6 Oleh: Herman, Skom., MM
Pemrograman Jejaring Komputer: Pertemuan 6 Oleh: Herman, Skom., MM
Jejaring Komputer
Pertemuan 6
Oleh: Herman, SKom., MM.
InetAddress class
• Kelas ini digunakan untuk mengambil informasi IP suatu
komputer. Kelas ini bersifat static dan tidak memiliki
konstruktor;
• Metoda-metodanya adalah:
– getByName(namahost) yang akan menerima sebuah string
nama host dan mengembalikan alamat IP berdasarkan DNS,
berupa object InetAddress. Untuk menampilkannya: gunakan
method toString();
– getLocalHost() yang akan mengembalikan alamat IP dan
nama host pada komputer lokal;
– getAllByName(namahost) mengembalikan array
InetAddress;
• Kemungkinan error: UnknownHostException.
Contoh getByName:
import java.net.*;
import java.util.*;
class IPFinder {
public static void main(String[] args) {
String host;
Scanner input= new Scanner(System.in);
System.out.print(“\n\nEnter host name: ”);
host= input.next();
try {
InetAddress address= InetAddress.getByName(host);
System.out.println(“IP Address: “+ address.toString());
} catch (UnknownHostException uhEx)
System.out.println(“Could not find: “+ host);
}
}
Contoh getLocalHost:
import java.net.*;
class MyLocalIPAddress {
public static void main(String[] args) {
try {
InetAddress address= InetAddress.getLocalHost();
System.out.println(address);
} catch (UnknownHostException uhEx)
System.out.println(“Could not find local address!”);
}
}
Contoh getAllByName:
import java.net.*;
class jejaring {
public static void main(String[] args) {
try {
InetAddress[] addresses=InetAddress.getAllByName(“ls0213”);
for(int i=0; i<addresses.length; i++)
System.out.println(addresses[i]);
InetAddress mesin= InetAddress.getLocalHost();
String lokal= mesin.getHostName();
String ip= mesin.getHostAddress();
System.out.println(“Mesin: “+ mesin);
System.out.println(“Lokal: “+ lokal);
System.out.println(“IP : “+ ip);
} catch (UnknownHostException uhEx){
System.out.println(“Could not find the addresses!”);
}
}
}
NSLookup Clone 1/5
• Menggunakan InetAddress
• Lihat HostLookup.java (ada di buku)
import java.net.*;
import java.io.*;
public class HostLookup {
public static void main (String[] args) {
if (args.length > 0) { // use command line
for (int i = 0; i < args.length; i++) {
System.out.println(lookup(args[i]));
}
} else {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
NSLookup Clone 2/5
System.out.println("Enter names and IP addresses.
Enter \"exit\" to quit.");
try {
while (true) {
String host = in.readLine( );
if (host.equals("exit")) break;
System.out.println(lookup(host));
}
} catch (IOException e) {
System.err.println(e);
}
}
} /* end main */
NSLookup Clone 3/5
private static String lookup(String host) {
InetAddress thisComputer;
byte[] address;
// get the bytes of the IP address
try {
thisComputer = InetAddress.getByName(host);
address = thisComputer.getAddress( );
} catch (UnknownHostException e) {
return "Cannot find host " + host;
}
if (isHostName(host)) {
// Print the IP address
String dottedQuad = "";
NSLookup Clone 4/5
for (int i = 0; i < address.length; i++) {
int unsignedByte= address[i]<0 ?
address[i]+256:address[i];
dottedQuad += unsignedByte;
if (i != address.length-1) dottedQuad += ".";
}
return dottedQuad;
} else { // this is an IP address
return thisComputer.getHostName( );
}
} // end lookup
NSLookup Clone 5/5
private static boolean isHostName(String host) {
char[] ca = host.toCharArray( );
// if we see a character that is neither a digit nor a period
// then host is probably a host name
for (int i = 0; i < ca.length; i++) {
if (!Character.isDigit(ca[i])) {
if (ca[i] != '.') return true;
}
}
// Everything was either a digit or a period
// so host looks like an IP address in dotted quad format
return false;
} // end isHostName
} // end HostLookup
Contoh Keluaran
% java HostLookup utopia.poly.edu
128.238.3.21
% java HostLookup 128.238.3.21
utopia.poly.edu
% java HostLookup
Enter names and IP addresses. Enter "exit" to quit.
cs.nyu.edu
128.122.80.78
199.1.32.90
star.blackstar.com
localhost
127.0.0.1
Informasi Antar muka Jejaring
• Untuk mendapatkan informasi network
interface pada Java telah terdapat kelas
NetworkInterface yang mampu
mendapatkan informasi tentang antar
muka jejaring, nama device, dan IP yang
ter-bind. Nama device misalnya eth0, lo0;
• Contoh: InterfaceLister.java. (3rd Ed)
InterfaceLister.java
import java.net.*;
import java.util.*;
• Metoda-metodanya:
public Socket accept() throws IOException
public void close() throws IOException
Prinsip Kerja ServerSocket dan
Socket 1/3
• ServerSocket
1. Menciptakan objek ServerSocket:
• ServerSocket servSock = new ServerSocket(1234);
2. Meletakkan server dalam keadaan menunggu:
• Socket link = servSock.accept();
3. Menyiapkan stream input dan output:
• Scanner input = new Scanner(link.getInputStream());
• PrintWriter output = new
PrintWriter(link.getOutputStream(),true);
4. Kirim dan terima data:
• output.println("Awaiting data...");
• String input = input.nextLine();
5. Tutup koneksi (setelah penyelesaian dialog).
• link.close();
Prinsip Kerja ServerSocket dan
Socket 2/3
• Prinsip Socket (client)
1. Mendirikan koneksi ke server, dibutuhkan alamat IP server dari tipe InetAddress
dan nomor port yang seharusnya untuk layanan tersebut:
• Socket link = new Socket(InetAddress.getLocalHost(),1234);
2. Menyiapkan stream input dan output:
• Scanner input = new Scanner(link.getInputStream());
• PrintWriter output = new
PrintWriter(link.getOutputStream(),true);
3. Kirim dan terima data:
• Objek Scanner pada klien akan menerima pesan-pesan yang dikirim objek PrintWriter
pada server,
• secara bersamaan objek PrintWriter pada klien akan mengirimkan pesan-pesan yang
diterima oleh objek Scanner di server menggunakan metoda nextLine dan println
secara berurutan.
4. Tutup koneksi.
Prinsip Kerja ServerSocket dan
Socket 3/3
Contoh TCPEchoServer 1/2:
import java.net.*; // for Socket, ServerSocket, and InetAddress
import java.io.*; // for IOException and Input/OutputStream
InputStream in = clntSock.getInputStream();
OutputStream out = clntSock.getOutputStream();
public InfoClient() {
try {
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket(TargetHost, INFO_PORT);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
Contoh InfoClient 2/3
System.out.println(inFromServer.readLine());
System.out.println(inFromServer.readLine());
System.out.println(inFromServer.readLine());
System.out.println("");
boolean isQuit = false;
while (!isQuit) {
System.out.print("Perintah Anda : ");
String cmd = inFromUser.readLine();
cmd = cmd.toUpperCase();
if (cmd.equals(QUIT)) {
isQuit = true;
}
outToServer.writeBytes(cmd + "\n");
String result = inFromServer.readLine();
System.out.println("Dari Server: " + result);
}
Contoh InfoClient 3/3
outToServer.close();
inFromServer.close();
clientSocket.close();
} catch (IOException ioe) {
System.out.println("Error:" + ioe);
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
public static void main(String[] args) {
new InfoClient();
}
}
Contoh InfoServer 1/3
import java.io.*;
import java.net.*;
import java.util.*;
public InfoServer() {
BufferedReader inFromClient;
DataOutputStream outToClient;
Socket serverSocket;
try {
ServerSocket infoServer =
new ServerSocket(INFO_PORT);
System.out.println("Server telah siap...");
Contoh InfoServer 2/3
while (true) {
serverSocket = infoServer.accept();
System.out.println("Ada client " + "yang terkoneksi!");
inFromClient = new BufferedReader(new
InputStreamReader(serverSocket.getInputStream()));
outToClient = new DataOutputStream(serverSocket.getOutputStream());
outToClient.writeBytes("InfoServer versi 0.1\n"+ "hanya untuk testing..\n"+
"Silahkan berikan perintah TIME | NET | QUIT\n");
boolean isQUIT = false;
while (!isQUIT) {
datafromClient = inFromClient.readLine();
if (datafromClient.startsWith("TIME")) {
outToClient.writeBytes(new Date().toString() + "\n");
} else if (datafromClient.startsWith("NET")) {
outToClient.writeBytes(InetAddress.getByName("LS0213").toString() + "\n");
} else if (datafromClient.startsWith("QUIT"))
{
isQUIT = true;
}
}
Contoh InfoServer 3/3
outToClient.close();
inFromClient.close();
serverSocket.close();
System.out.println("Koneksi client tertutup..");
}
} catch (IOException ioe) {
System.out.print("error: " + ioe);
} catch (Exception e) {
System.out.print("error: " + e);
}
}
/* program utama */
public static void main(String[] args) {
new InfoServer();
}
}
Contoh PortScanner 1/2:
import java.net.*;
import java.io.*;
if (args.length > 0) {
host = args[0];
}
Socket connection = null;
try {
InetAddress theAddress = InetAddress.getByName(host);
for (int i = 1; i < 65536; i++) {
try {
connection = new Socket(host, i);
localAddr=(InetSocketAddress) connection.getLocalSocketAddress();
Contoh PortScanner 2/2:
remoteAddr=(InetSocketAddress) connection.getRemoteSocketAddress();
System.out.println("There is a server on port “ + remoteAddr +
" and connected to "+localAddr);
} catch (IOException e) { // must not be a server on this port
}
} // end for
} catch (UnknownHostException e) {
System.err.println(e);
}
finally {
try {
if (connection != null) connection.close( );
} catch (IOException e) {}
}
} // end main
} // end PortScanner