Pemrograman Jejaring Komputer: Pertemuan 6 Oleh: Herman, Skom., MM

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Pemrograman

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.*;

public class InterfaceLister {


public static void main(String[] args) throws Exception {
Enumeration interfaces = NetworkInterface.getNetworkInterfaces( );
while (interfaces.hasMoreElements( )) {
NetworkInterface ni = (NetworkInterface) interfaces.nextElement( );
System.out.println(ni);
}
}
}
Contoh Keluaran
% java InterfaceLister
name:eth1 (eth1) index: 3 addresses:
/192.168.210.122;
name:eth0 (eth0) index: 2 addresses:
/152.2.210.122;
name:lo (lo) index: 1 addresses:
/127.0.0.1;
Connection-oriented dan
Connectionless Socket
• Pemrograman socket dapat memanfaatkan UDP
(User Datagram Protocol) maupun TCP
(Transmission Control Protocol);
• Socket yang menggunakan UDP untuk transport
dikenal dengan datagram sockets, sedangkan
socket yang memakai TCP disebut stream
sockets/TCP sockets.
IP Protocol Suite
Review: TCP vs. UDP
• TCP
– Connection-oriented
– Reliable
– Stateful
• UDP
– Connectionless
– Unreliable
– Stateless
Komunikasi Socket ke Socket
Review: Ports
• Digunakan untuk membedakan aplikasi-
aplikasi yang berjalan di host/alamat yang
sama;
• Direpresentasikan sebagai integer 16-bit:
– Port-port yang dikenal: 0 – 1023
– Terdaftar: 1024 – 49151
– Port-port dinamis: 49152 - 65535
Socket
• Socket adalah sebuah
abstraksi perangkat
lunak yang digunakan
sebagai suatu "terminal"
dari suatu hubungan
antara dua mesin atau
proses yang saling
berinterkoneksi.

2009 Pemrograman Jejaring 20


Operasi Socket
• Socket dapat melakukan operasi:
– Koneksi ke mesin remote
– Mengirim data
– Menerima data
– Mentutup koneksi
– Bind to a port
– Listen pada data yang masuk
– Menerima koneksi dari mesin remote pada port tertentu
• Di setiap mesin yang saling berinterkoneksi, harus
terpasang socket.
Socket API dalam Java
• Pada J2SE telah disediakan paket java.net yang
berisi kelas- kelas dan interface yang
menyediakan API (Application Programming
Interface):
– level rendah (Socket, ServerSocket,
DatagramSocket)
– level tinggi (URL, URLConnection).
• Disimpan pada package java.net.*
Kelas Java Socket dan
ServerSocket
• Socket Connection Oriented Programming:
– This means that the connection between server and client remains open
throughout the duration of the dialogue between the two and is only
broken (under normal circumstances) when one end of the dialogue
formally terminates the exchanges (via an agreed protocol)
• Kelas java.net.ServerSocket digunakan oleh Server untuk
mendengarkan koneksi;
• Kelas java.net.Socket digunakan oleh klien untuk inisialisasi
koneksi;
• Setelah klien terkoneksi ke server dengan menggunakan Socket,
maka ServerSocket akan mengembalikan status server ke klien
melalui koneksi yang terbentuk sebelumnya.
Kelas Java.net.Socket 1/2
• Koneksi dicapai melalui konstruktor-konstruktor.
• Setiap objek Socket diasosiasikan dengan hanya satu
remote host. Untuk tersambung dengan host lain, kita
harus menciptakan objek Socket baru:

public Socket(String host, int port) throws


UnknownHostException, IOException
public Socket(InetAddress address, int port) throws
IOException
public Socket(String host, int port, InetAddress
localAddress, int localPort) throws IOException
public Socket(InetAddress address, int port, InetAddress
localAddress, int localPort) throws IOException
Kelas Java.net.Socket 2/2
• Kirim dan terima data dicapai dengan output dan input
streams.
• Metoda-metoda untuk mendapatkan input stream dan
output stream untuk socket:
public InputStream getInputStream() throws
IOException
public OutputStream getOutputStream() throws
IOException

• Metoda untuk menutup socket:


public void close() throws IOException
Kelas Java.net.ServerSocket 1/2
• Kelas java.net.ServerSocket merepresentasikan socket
dari server.
• Server socket dikonstruksikan pada port tertentu. Lalu
memanggil accept() untuk mendengarkan koneksi-
koneksi yang datang:
– Pertama accept() mem-blok pemanggil sampai sebuah koneksi
dideteksi;
– Lalu accept() mengembalikan objek java.net.Socket yang
digunakan untuk melakukan komunikasi aktual dengan klien;
Kelas Java.net.ServerSocket 2/2
• Konstruktor-konstruktornya:
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws
IOException
public ServerSocket(int port, int backlog, InetAddress
bindAddr)throws IOException

• 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

public class TCPEchoServer {


private static final int BUFSIZE = 32; // Size of receive buffer

public static void main(String[] args) throws IOException {


if (args.length != 1) // Test for correct # of args
throw new IllegalArgumentException("Parameter(s): <Port>");
int servPort = Integer.parseInt(args[0]);
// Create a server socket to accept client connection requests
ServerSocket servSock = new ServerSocket(servPort);
int recvMsgSize; // Size of received message
byte[] byteBuffer = new byte[BUFSIZE]; // Receive buffer
Contoh TCPEchoServer 2/2:
for (;;) { // Run forever, accepting and servicing connections
Socket clntSock = servSock.accept(); // Get client connection

System.out.println("Handling client at " +


clntSock.getInetAddress().getHostAddress() + " on port "+
clntSock.getPort());

InputStream in = clntSock.getInputStream();
OutputStream out = clntSock.getOutputStream();

// Receive until client closes connection, indicated by -1 return


while ((recvMsgSize = in.read(byteBuffer)) != -1)
out.write(byteBuffer, 0, recvMsgSize);
clntSock.close(); // Close the socket. We are done with this client!
}
/* NOT REACHED */
}
}
Contoh TCPEchoClient 1/2:
import java.net.*; // for Socket
import java.io.*; // for IOException and Input/OutputStream

public class TCPEchoClient {

public static void main(String[] args) throws IOException {


if ((args.length < 2) || (args.length > 3)) // Test for correct # of args
throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]");

String server = args[0]; // Server name or IP address


// Convert input String to bytes using the default character encoding
byte[] byteBuffer = args[1].getBytes();
int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;

// Create socket that is connected to server on specified port


Socket socket = new Socket(server, servPort);
System.out.println("Connected to server...sending echo string");
Contoh TCPEchoClient 2/2:
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(byteBuffer); // Send the encoded string to the server

// Receive the same string back from the server


int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd; // Bytes received in last read
while (totalBytesRcvd < byteBuffer.length) {
if ((bytesRcvd = in.read(byteBuffer, totalBytesRcvd,
byteBuffer.length - totalBytesRcvd)) == -1)
throw new SocketException("Connection close prematurely");
totalBytesRcvd += bytesRcvd;
}
System.out.println("Received: " + new String(byteBuffer));
socket.close(); // Close the socket and its streams
}
}
Contoh InfoClient 1/3
import java.net.*;
import java.io.*;
import java.util.*;

public class InfoClient {


private final int INFO_PORT=50000;
private final String TargetHost = "localhost";
private final String QUIT = "QUIT";

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 class InfoServer {


private final int INFO_PORT=50000;
private String datafromClient;

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.*;

public class PortScanner {


public static void main(String[] args) {
String host = "localhost";
InetSocketAddress localAddr, remoteAddr;

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

You might also like