0% found this document useful (0 votes)
13 views

Chapter 3 Networking and Security

Chapter 3 covers the basics of networking and security, focusing on concepts such as sockets, TCP, UDP, and proxy servers. It explains the Java InetAddress and URL classes, detailing their methods for handling IP addresses and URLs. Additionally, it introduces the URLConnection class for managing communication links between URLs and applications.

Uploaded by

hamoh57753
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter 3 Networking and Security

Chapter 3 covers the basics of networking and security, focusing on concepts such as sockets, TCP, UDP, and proxy servers. It explains the Java InetAddress and URL classes, detailing their methods for handling IP addresses and URLs. Additionally, it introduces the URLConnection class for managing communication links between URLs and applications.

Uploaded by

hamoh57753
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Chapter 3

Networking & Security

Basics of Networking:

Socket
A socket is one end-point of a two-way communication link between two programs running on the
network.
A server application normally listens to a specific port waiting for connection requests from a client.
When a connection request arrives, the client and the server establish a dedicated connection over which
they can communicate. During the connection process, the client is assigned a local port number, and
binds a socket to it. The client talks to the server by writing to the socket and gets information from the
server by reading from it. Similarly, the server gets a new local port number (it needs a new port number
so that it can continue to listen for connection requests on the original port). The server also binds a
socket to its local port and communicates with the client by reading from and writing to it.
The java.net package in the Java development environment provides a class--Socket--that represents one
end of a two-way connection between your Java program and another program on the network. The
Socket class implements the client side of the two-way link. If you are writing server software, you will
also be interested in the ServerSocket class which implements the server side of the two-way link. This
lesson shows you how to use the Socket and ServerSocket classes.

Transmission Control Protocol(TCP):


TCP stands for Transmission Control Protocol, which allows for reliable communication between
two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
TCP is often described as a byte stream, connection-oriented, reliable delivery transport layer
protocol
User Datagram Protocol:(UDP)
The User Datagram Protocol (UDP) is simplest Transport Layer communication protocol
available of the TCP/IP protocol suite. It involves minimum amount of communication
mechanism. UDP is said to be an unreliable transport protocol but it uses IP services which
provides best effort delivery mechanism.
In UDP, the receiver does not generate an acknowledgement of packet received and in turn,
the sender does not wait for any acknowledgement of packet sent. This shortcoming makes
this protocol unreliable as well as easier on processing.

Features
• UDP is used when acknowledgement of data does not hold any significance.
• UDP is good protocol for data flowing in one direction.
• UDP is simple and suitable for query based communications.
• UDP is not connection oriented.
• UDP does not provide congestion control mechanism.
• UDP does not guarantee ordered delivery of data.
• UDP is stateless.
• UDP is suitable protocol for streaming applications such as VoIP, multimedia streaming.

Proxy server :
A proxy server is a computer that offers a computer network service to allow clients to make
indirect network connections to other network services. A client connects to the proxy server, then
requests a connection, file, or other resource available on a different server. The proxy provides the
resource either by connecting to the specified server or by serving it from a cache. In some cases,
the proxy may alter the client's request or the server's response for various purposes.
A proxy server is a dedicated computer or a software system running on a computer that acts as an
intermediary between an endpoint device, such as a computer, and another server from which a user
or client is requesting a service. The proxy server may exist in the same machine as a firewall server
or it may be on a separate server, which forwards requests through the firewall.
An advantage of a proxy server is that its cache can serve all users. If one or more Internet sites are
frequently requested, these are likely to be in the proxy's cache, which will improve user response
time. A proxy can also log its interactions, which can be helpful for troubleshooting.

What is Internet addressing?

A way to locate people, computers, and Internet resources. It can be


• IP (Internet Protocol) addresses and domain names
• Electronic mail addresses
• URLs
In general, Internet addressing is a systematic way to identify people, computers and Internet
resources.
On the Internet, the term "address" is used loosely. Address can mean many different things from an
electronic mail address to a URL.

Java InetAddress class


Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods
to get the IP of any host name for example www.google.com, www.facebook.com etc.

Methods of InetAddress class


1. boolean equals(Object obj)
Compares two IP addresses, returns true if there is a match.
2. byte[ ] getAddress( )
Returns the IP address in byte format.
3. static InetAddress [ ] getAllByName (String hostname)
Returns an array of InetAddress instances representing the hostname.
4. static InetAddress getByName (String hostname)
Returns an InetAddress instance representing the hostname.
5. String getHostAddress( )
Returns the IP address in dotted decimal format.
6. static InetAddress getLocalHost ( )
Returns the IP address of the localhost machine.
7. String getHostName( )
Returns the hostname of the InetAddress.
8. boolean isMulticastAddress( )
Returns true if the InetAddress is a multicast address (class D address).
The methods of InetAddress class may throw java.net.UnknownHostException,
java.lang.SecurityException
Example of Java InetAddress class
Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com website.

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

public class InetDemo{


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

InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());

}catch(Exception e){System.out.println(e);}
}
}

Output:
Host Name: www.javatpoint.com
IP Address: 206.51.231.148

Socket Class:
public class Socket

extends Object
This class implements client sockets (also called just "sockets"). A socket is an endpoint for
communication between two machines.
The actual work of the socket is performed by an instance of the SocketImpl class. An application,
by changing the socket factory that creates the socket implementation, can configure itself to create
sockets appropriate to the local firewall.
Socket

public Socket(String host,


int port) throws UnknownHostException, IOException

Creates a stream socket and connects it to the specified port on the specified host.
Parameters:
host - the host
port - the port

Socket
public Socket(String host,
int port,
boolean stream) throws IOException

Creates a socket and connects it to the specified port on the specified host. The last argument
lets you specify whether you want a stream or datagram socket.
Parameters:
host - the specified host
port - the specified port
stream - a boolean indicating whether this is a stream or datagram socket

Socket
public Socket(InetAddress address,
int port) throws IOException

Creates a stream socket and connects it to the specified address on the specified port.
Parameters:
address - the specified address
port - the specified port

Socket
public Socket(InetAddress address,
int port,
boolean stream) throws IOException
Creates a socket and connects it to the specified address on the specified port. The last
argument lets you specify whether you want a stream or datagram socket.
Parameters:
address - the specified address
port - the specified port
stream - a boolean indicating whether this is a stream or datagram socket

getInetAddress
public InetAddress getInetAddress()

Gets the address to which the socket is connected.

getPort
public int getPort()

Gets the remote port to which the socket is connected.

getLocalPort
public int getLocalPort()

Gets the local port to which the socket is connected.

getInputStream
public InputStream getInputStream() throws IOException

Gets an InputStream for this socket.

getOutputStream
public OutputStream getOutputStream() throws IOException

Gets an OutputStream for this socket.

close
public synchronized void close() throws IOException

Closes the socket.

toString
public String toString()
Converts the Socket to a String.
Overrides:
toString in class Object

ServerSocket class:

public class ServerSocket extends Object


implements Closeable

This class implements server sockets. A server socket waits for requests to come in over the
network. It performs some operation based on that request, and then possibly returns a result to the
requester.
The actual work of the server socket is performed by an instance of the SocketImpl class. An
application can change the socket factory that creates the socket implementation to configure itself
to create sockets appropriate to the local firewall.

ServerSocket

public ServerSocket(int port) throws IOException

Creates a server socket on a specified port.


Parameters:
port - the port

ServerSocket
public ServerSocket(int port,
int count) throws IOException

Creates a server socket, binds it to the specified local port and listens to it. You can connect to
an annonymous port by specifying the port number to be 0.
Parameters:
port - the specified port
count - the amt of time to listen for a connection

getInetAddress
public InetAddress getInetAddress()

Gets the address to which the socket is connected.

getLocalPort
public int getLocalPort()

Gets the port to which the socket is listening on

accept
public Socket accept() throws IOException

Accepts a connection. This method will block until the connection is made.

close
public void close() throws IOException

Closes the server socket.

toString
public String toString()

Returns the implementation address and implementation port of this ServerSocket as a String.
Overrides:
toString in class Object

setSocketFactory
public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException
Sets the system's server SocketImplFactory. The factory can be specified only once.
Parameters:
fac - the desired factory
Throws: SocketException
If the factory has already been defined.

URL:
URL stands for Uniform Resource Locator, and is used to specify addresses on the World
Wide Web. A URL is the fundamental network identification for any resource connected to
the web (e.g., hypertext pages, images, and sound files).
URL Class Methods:

The java.net.URL class represents a URL and has complete set of methods to manipulate URL in
Java.
The URL class has several constructors for creating URLs, including the following:

SN Methods with Description


public URL(String protocol, String host, int port, String file) throws
1 MalformedURLException.
Creates a URL by putting together the given parts.
public URL(String protocol, String host, String file) throws MalformedURLException
2 Identical to the previous constructor, except that the default port for the given protocol is used.
public URL(String url) throws MalformedURLException
3 Creates a URL from the given String
public URL(URL context, String url) throws MalformedURLException
4 Creates a URL by parsing the together the URL and String arguments

The URL class contains many methods for accessing the various parts of the URL being
represented. Some of the methods in the URL class include the following:

SN Methods with Description


public String getPath()
1 Returns the path of the URL.
public String getQuery()
2 Returns the query part of the URL.
public String getAuthority()
3 Returns the authority of the URL.
public int getPort()
4 Returns the port of the URL.
public int getDefaultPort()
5 Returns the default port for the protocol of the URL.
public String getProtocol()
6 Returns the protocol of the URL.
public String getHost()
7 Returns the host of the URL.
public String getHost()
8 Returns the host of the URL.
public String getFile()
9 Returns the filename of the URL.
Java URLConnection class
The Java URLConnection class represents a communication link between the URL and the
application. This class can be used to read and write data to the specified resource referred by the
URL.

How to get the object of URLConnection class


The openConnection() method of URL class returns the object of URLConnection class. Syntax:
1. public URLConnection openConnection()throws IOException{}

Displaying source code of a webpage by URLConnecton class


The URLConnection class provides many methods, we can display all the data of a webpage by
using the getInputStream() method. The getInputStream() method returns all the data of the
specified URL in the stream that can be read and displayed.

import java.io.*;
import java.net.*;
public class DisplayData {
public static void main(String[] args){
try{

URL url=new URL("http://localhost:9999/dec17/");


URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}

}catch(Exception e){System.out.println(e);}
}
}

Mehtods:
getURL

public URL getURL()

Returns the value of this URLConnection's URL field.

Returns:
the value of this URLConnection's URL field.
See Also:
url

getContentLength
public int getContentLength()

Returns the value of the content-length header field.

Returns:
the content length of the resource that this connection's URL references, or -1 if the
content length is not known.

getContentType
public String getContentType()

Returns the value of the content-type header field.

Returns:
the content type of the resource that the URL references, or null if not known.
See Also:
getHeaderField

getContentEncoding
public String getContentEncoding()

Returns the value of the content-encoding header field.

Returns:
the content encoding of the resource that the URL references, or null if not known.
See Also:
getHeaderField

getExpiration
public long getExpiration()

Returns the value of the expires header field.

Returns:
the expiration date of the resource that this URL references, or 0 if not known. The
value is the number of seconds since January 1, 1970 GMT.
See Also:
getHeaderField

getDate
public long getDate()

Returns the value of the date header field.

Returns:
the sending date of the resource that the URL references, or 0 if not known. The value
returned is the number of seconds since January 1, 1970 GMT.
See Also:
getHeaderField

getLastModified
public long getLastModified()

Returns the value of the last-modified header field. The result is the number of seconds since
January 1, 1970 GMT.

Returns:
the date the resource referenced by this URLConnection was last modified, or 0 if not
known.
See Also:
getHeaderField

getHeaderField
public String getHeaderField(String name)

Returns the name of the specified header field.

Parameters:
name - the name of a header field.
Returns:
the value of the named header field, or null if there is no such field

You might also like