NETWORK PROGRAMMING
INET ADDRESS
Ip Address:
Devices connected to the internet are called nodes. Nodes that are computers are called hosts.
Ip stands for Internet Protocol and each node or host is identified by a unique number
called an Internet address or an IP address.
Ip address (IPV4)
Every node in the computer network is identified with the help of ip address and they are
logical address
Since ip address can be changed on the basis of the location of the device, they are termed as
logical address
We can assign the ip address manually or dynamically
Represented in decimal and has four octets (X.X.X.X)
[Link] to [Link] (32 bits)
How to see the ip address of the device??
Command Prompt
Command: ipconfig
Mac address
Mac address stands for Media access control
Every node in the LAN is identified using the mac address
Analogy:
IP address=Location of a person
Mac address=Name of a person
(Wherever a person goes to different places his location gets changed but name won’t)
Routers need ip address whereas switches need mac address
i.e. IP addresses are the router friendly addresses whereas mac addresses are the switch
friendly addresses
Mac address are physical address i.e. hardware address
It is unique and cannot be changed
Assigned by manufacturer and is represented in hexadecimal (48 bits)
How to see the mac address of the device??
Command Prompt:
Command>ipconfig/all
Mac addresses are separated by hyphen(-), period(.) or colon(:)
Port address
Analogy:
Suppose a parcel is delivered from point A to point B
Reaching our city=Reaching our network(IP address)
Reaching our apartment=Reaching the host(Mac address)
Reaching the right person=Reaching the right process(Port address)\
In real communication any device can be identified by ip address and mac address, but in that
host many processes might be running
To which process the data has to reach is decided by the port address.
Every process in the node is identified by the port numbers or port address
Port=Communication endpoint
If you open google chrome, a new process will be started and the port number for that process
would be assigned by the operating system.
The value would range from (0-65535)
How to see the port numbers ??
Type: resource monitor
Points to remember:
Before sending the data, any node must:
Attach source ip address and destination ip address
Attach source mac address and destination mac address
Attach source port number and destination port number
Ip address (IPv6)
IPv6 (Internet Protocol version 6) addresses are 128-bit identifiers for devices on an IPv6
network
They are designed to replace the older IPv4 addresses due to the limited address space of
IPv4
Here's an overview of IPv6 addresses:
128 bits:
IPv6 addresses are 128 bits long, compared to IPv4's 32 bits
Hexadecimal Notation:
They are written as eight groups of four hexadecimal digits, separated by colons (e.g.,
2001:0db8:85a3:0000:0000:8a2e:0370:7334)
Communication Protocol
In communication, Protocol is a set of standard rules that the communicating parties — the sender, the
receiver, and all other intermediate devices need to follow.
For example, while flying an airplane, pilots obey very specific rules for communication with other
airplanes and with air traffic control.
We need protocols for different reasons such as flow control, access control, etc.
Flow control is required when the sender and receiver have different speeds of sending and receiving
the data
Computer A is sending data at the speed of 1024 Mbps and computer B is receiving data at the speed
of 512 Mbps. In this case, Computer B must be able to inform computer A about the speed mismatch
so that computer A can adjust its data transmission rate. Otherwise some data will be lost.
Access control is required to decide which nodes in a communication channel will access the link
shared among them at a particular instant of time. Otherwise, the transmitted data packets will collide
if computers are sending data simultaneously through the same link, that result in the loss or
corruption of data.
Protocols also define:
how to decide whether the data received is for that node or to be forwarded to another node.
ensuring that all the data have reached the destination without any loss.
how to rearrange the packets and process them at the destination.
Open System Interconnection (OSI) Model
OSI model defines and helps understand how data is transferred from one computer to
another in a computer network.
Example: If one computer is based on microsoft windows, and another has mac-os installed,
then how these computers are going to successfully communicate with each other is described
by OSI model.
OSI model was developed by the International Organization for Standardization (ISO) in 1984, and it
is now considered as an architectural model for the inter-computer communications.
OSI model divides the whole task into seven smaller and manageable tasks.
Each layer is assigned a particular task.
Each layer is self-contained, so that task assigned to each layer can be performed independently.
A list of seven layers are given below:
1. Physical Layer
2. Data-Link Layer
3. Network Layer
4. Transport Layer
5. Session Layer
6. Presentation Layer
7. Application Layer
Application Layer
It is the top most layer of OSI Model
Application layer interacts with an application program
The application layer is closest to the end-user
It means this layer allows users to interact with other software application
This layer provide services for the network applications
The Application Layer contains a variety of protocols that are commonly needed by users such
as HTTP, FTP, SMTP, etc.
Presentation Layer
Presentation layer takes care that the data is sent in such a way that the receiver will
understand the information(data) and will be able to use the data
Presentation Layer receives data from application layer
This data is in the form of characters and numbers
This layer converts these characters and numbers to machine understandable format (binary)
i.e. Presentation layer plays a role translator
It carries out encryption at the transmitter and decryption at the receiver
It carries out data compression to reduce the bandwidth of the data to be transmitted
The primary role of Data compression is to reduce the number of bits to be transmitted
It is important in transmitting multimedia such as audio, video, text etc.
Session Layer
The Session Layer allows users on different machines to establish active communication sessions
between them
It's main aim is to establish, maintain and synchronize the interaction between communicating systems
This layer ensures that data is sent successfully
Transport Layer
The basic function of the Transport layer is to accept data from the layer above, split it up into smaller
units called segments, and pass these data units to the Network layer
A message is divided into segments; each segment contains sequence number, which helps to
reassemble the segments in the correct order
Error Control is performed in this layer
If the data does not arrive the destination, this layer uses schemes to retransmit the data
Transmission Control Protocol (TCP) resides in this layer
Network Layer
This layer works for the transmission of the received data segments from one computer to
another located in different networks
Data unit in this layer are called packets
Routers and gateways operate in the network layer
The functions of network layer are:
Logical addressing
-ip addressing is performed in this layer. Every computer in the network has an unique ip
address. This layer assigns senders and receivers ip address to each segment to form an ip
packet.
ip address are assigned to ensure that each packet reaches the correct destination
Path determination and routing
the process of selecting a reliable and best path between a sender and receiver, and
transmitting the packet in the correct receiver.
Data link layer
Data Packets from Network layer comes in this layer. Data packets contain ip address of
sender and receiver
There are two kind of addressing:
Logical addressing (It is done at network layer)
Physical addressing (mac address of sender and receiver are asssigned to each data packet to
form a frame)
Physical Layer:
Physical layer is the lowest layer of the OSI reference model. It is responsible for sending bits
from one computer to another.
This layer acts as an interface between transmission media and device.
Data in this layer consists of stream of bits. The bits must be encoded into signals for
transmission.
It defines the type of encoding i.e. how 0's and 1's are changed to signal.
TCP/IP (Transmission Control Protocol/Internet Protocol)
It is a suite of communication protocols used to interconnect network devices on the
internet
TCP/IP specifies how data is exchanged over the internet, and how data should be
formatted so other networked device can understand
It provides the rules and standards that allow different devices and networks to communicate
effectively, ensuring data can be sent, received, and understood across diverse systems
Key Features of TCP/IP
End node verification:
The two end point of any data transfer are responsible for making sure that it was successful
No centralized control system
Dynamic Routing:
End node can transfer data over multiple paths
The key network issues are:
Addressing, Routing, Name Resolution, Flow and error control, Interoperability
Transmission Control Protocol (TCP)
Ensures reliable transmission of data between devices
It establishes a connection and ensures that data is delivered in order and without errors
User Datagram Protocol (UDP)
Provides a connectionless datagram service that emphasizes reduced latency over reliability
It's useful for applications where speed is critical and occasional data loss is acceptable, like
video streaming or online gaming
The TCP/IP model has four abstraction layers, each with specific protocols and functions:
Application Layer
Functions: Provides end-user services and network applications.
Protocols: HTTP, FTP, SMTP, DNS, etc.
Transport Layer
Functions: Ensures end-to-end communication, error-checking, and data flow control.
Protocols: TCP, UDP
Internet Layer
Functions: Determines the best path through the network.
Protocols: IP (IPv4, IPv6),
Network Access Layer (Link Layer)
Functions: Defines protocols for data exchange between network devices on the same network segment.
Protocols: Ethernet, Wi-Fi, etc.
Functions of TCP/IP Protocols
Addressing and Routing
IP Addresses: Unique identifiers assigned to each device on a network.
Routing: Determines the path data packets take from the source to the destination
Data Transmission
TCP: Provides reliable, ordered, and error-checked delivery of data.
UDP: Offers a faster, but less reliable transmission method.
Error Detection and Correction
Ensures data integrity and retransmits lost or corrupted packets
Flow Control
Manages the rate of data transmission to prevent network congestion
Examples of TCP/IP Usage
Web Browsing (HTTP/HTTPS over TCP/IP)
HTTP and HTTPS are protocols that enable the fetching of resources, such as HTML documents
They use TCP to ensure reliable data transfer
Email (SMTP over TCP/IP)
SMTP is used for sending emails. It relies on TCP for ensuring the email data is reliably transferred
from the client to the server
File Transfer (FTP over TCP/IP)
FTP allows users to transfer files between computers on a network. It uses TCP to guarantee that all
parts of the file are delivered correctly
Streaming Media (RTP over UDP/IP)
RTP is used in conjunction with UDP for delivering real-time audio and video. While UDP does not
ensure reliable delivery, it is faster and suitable for time-sensitive data like streaming.
InetAddress class
The [Link] is the high level representation of an IP address, both ipv4 and ipv6
Creating new InetAddress objects
There are no public constructors in the InetAddress class.
Instead, the InetAddress has a static factory method that connects to a DNS server to resolve a
hostname
The most common is [Link]()
Syntax:
InetAddress address=[Link]("[Link]")
This method makes a connection to the local DNS server to look up the name and the
numeric address
If the DNS server can’t find the address, this method throws an UnknownHostException
Example: A program that prints the address of [Link]
The reverse lookup by IP address can also be done
i.e. If you want the hostname for the address [Link], pass the dotted quad address to
the [Link]()
If the address you look up to does not have a hostname, getHostName() simply returns the
dotted quad address you supplied
Try it yourself….
The InetAddress class contains four getter methods that return the hostname as a string and IP
address as both a string and a byte array
Public string getHostName()
Public string getCanonicalHostName()
Public byte[] getAddress()
Public string getHostAddress()
There are no corresponding setHostName() and setAddress() methods, which means that
packages outside [Link] cant change an InetAddress objects field behind its back
This makes InetAddress immutable
The getHostName() method returns the host name associated with the IP address
Example:
The getCanonicalHostName() method is similar, but it is more aggressive about contacting
DNS.
getHostName() will only call the DNS if it doesn’t think it already knows the hostname
getCanonicalHostName() call DNS if it can, and may replace the existing cached hostname
i.e. it returns the fully qualified domain name (FQDN) of the host, which may involve
additional DNS lookups to obtain the most accurate and complete name
Run this code and observe the output.
The getHostAddress() method returns a string containing the dotted quad format of the IP
address.
Example: To print the IP address of the local machine
The getAddress() returns the raw IP address of the InetAddress object in the form of a byte
array
InetAddress address = [Link]();
byte[] add = [Link]();
This method is useful when you need to manipulate the IP address at a lower level or convert
it into a different format.
Example: Determine whether a IP address is v4 or v6
Next Slide
Address Types
Some IP addresses and some patterns of addresses have special meaning. For instance,
[Link] is the loopback address.
IPv4 addresses in the range [Link] to [Link] are multicast addresses that send to
several subscribed host at once.
Java includes different methods for testing whether an InetAddress object meets any of these
criteria.
Public Boolean isAnyLocalAddress():
This method returns true if the address is wildcard address, false otherwise.
Wildcard addresses are used in network programming to allow a server to listen for incoming
connections on any of the available network interfaces.
Imagine a server with the following network interfaces and IP addresses:
Ethernet: [Link]
Wi-Fi: [Link]
If the server application binds to [Link], it will accept connections on both [Link] and
[Link].
Example:
The isAnyLoopbackAddress() method in Java is used to check if an IP address is a loopback
address.
Loopback addresses ([Link] for IPv4 and ::1 for IPv6) are used for local communication
and testing
Example:
The isMulticastAddress() method in Java's InetAddress class is used to check whether an IP
address is a multicast address
Multicast addresses are used for one-to-many communication, where data sent by a sender
can be received by multiple recipients
This is in contrast to unicast communication, where data is sent from one sender to one
recipient, and broadcast communication, where data is sent from one sender to all possible
recipients within a network
IPv4 Multicast Address Range: IPv4 multicast addresses are in the range of [Link] to
[Link]
IPv6 Multicast Address Prefix: IPv6 multicast addresses start with the prefix FF00::/8
Applications such as video streaming, online gaming, and multicast messaging systems use
multicast addresses to efficiently distribute data to multiple recipients simultaneously
For example, in video streaming, a server can send a single video stream to a multicast
address, and multiple clients can join the multicast group to receive the stream
Assignment:
There are other address types as well.
Do research and learn more about them.
Testing Reachability
The InetAddress class has two isReachable() methods that test whether a particular node is reachable
from the current host (i.e. whether a network connection can be made)
Connections can be blocked for many reasons, including firewalls, proxy servers, broken cables, or
simply the remote host is not turned on when you try to connect
public boolean isReachable(int timeout) throws IOException
public boolean isReachable(NetworkInterface interface,int ttl,int timeout) throws IOException
Network Interface: Specifies the network interface through which the connection should be attempted.
If null, the system will determine the appropriate network interface
TTL (Time-to-Live) parameter specifies the maximum number of network hops (routers or gateways)
that a packet can traverse before being discarded
If the host responds within the timeout milliseconds, the method returns true; otherwise return false
IOException will be thrown if there's a network error
Administrators and developers use the isReachable() method to diagnose network
connectivity issues
For example, it can be used to check if a remote server is reachable from a client machine,
helping to troubleshoot network configuration problems
Object Methods
Like every other class, [Link] inherits from [Link]
Thus it has access to all the methods of that class
public boolean equals(Object obj)
public int hashCode()
public String toString()
equals(Object obj) in the InetAddress class is used to compare two InetAddress objects for
equality
hashCode() in the InetAddress class is used generate a hash code for the InetAddress object
toString() in the InetAddress class returns a string representation of the IP address
Inet4Address and Inet6Address are subclasses of the InetAddress class in Java, representing
IPv4 and IPv6 addresses, respectively
While both classes inherit methods and attributes from the InetAddress class, they are
specialized for handling IPv4 and IPv6 addresses, respectively
Inet4Address
Class: [Link].Inet4Address
Purpose: Represents IPv4 addresses, which are 32-bit addresses typically written in dotted-
decimal notation (e.g., [Link]).
Methods: Inherits methods from the InetAddress class and provides additional methods
specific to IPv4 addresses.
Usage: Used for working with and manipulating IPv4 addresses in Java applications.
Example:
InetAddress address = [Link]("[Link]");
Inet6Address
Class: [Link].Inet6Address
Purpose: Represents IPv6 addresses, which are 128-bit addresses typically written in
hexadecimal notation (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334).
Methods: Inherits methods from the InetAddress class and provides additional methods
specific to IPv6 addresses.
Usage: Used for working with and manipulating IPv6 addresses in Java applications.
Example:
InetAddress address=[Link]("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
Network Interface Class:
The NetworkInterface class in Java provides methods for querying and manipulating
network interfaces on the local machine
A network interface represents a network connection on a device, such as an Ethernet
adapter, Wi-Fi adapter, etc.
Because NetworkInterface objects represent physical hardware, they cannot be constructed
arbitrarily.
As with the InetAddress class, there are static factory methods that return the
NetworkInterface object associated with a particular network interface.
public static NetworkInterface getByName(String name) throws SocketException
The getByName() method returns a NetworkInterface object representing the network
interface with the particular name
The getNetworkInterfaces() method returns a [Link] listing all the network
interfaces on the local host.
Spam Checking
A program that checks if an IP address is listed in a spam database such as the Spamhaus
Block List can be useful in several scenarios, particularly in the context of network security
and email systems
Here are some situations where such a program would be necessary:
Spam Filtering: Email servers use spam lists to filter out emails from known spammers
Before accepting an email, the server can check the sender's IP address against a spam
database to decide whether to accept, reject, or flag the email
Blacklist Management: Automatically managing and updating IP blacklists to ensure that
known spammers are blocked from sending emails
Example Use Case: Email Server
Imagine you are running an email server for a company. You want to ensure that your users
are not bombarded with spam emails. To achieve this, you can integrate a spam check
mechanism in your email server that verifies the IP address of every incoming email against a
known spam database like Spamhaus
To find out if a certain IP address is a known spammer, reverse the bytes of the address, add
the domain of the blackhole service, and look it up
If the address is found, it's a spammer
If it isn't, it's not
Ex: if you want to ask [Link] if [Link] is a spammer, you would look up the
hostname [Link].[Link]