0% found this document useful (0 votes)
18 views22 pages

CN Assignment

The document provides an overview of various networking commands and their functions, including hostname, ipconfig, ping, nslookup, and others. It also outlines steps for establishing different network topologies using Cisco Packet Tracer, such as peer-to-peer, star, and mesh topologies, as well as the use of routers. Additionally, it explains the shortest path algorithm in networking and defines a socket as an endpoint for communication between programs.

Uploaded by

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

CN Assignment

The document provides an overview of various networking commands and their functions, including hostname, ipconfig, ping, nslookup, and others. It also outlines steps for establishing different network topologies using Cisco Packet Tracer, such as peer-to-peer, star, and mesh topologies, as well as the use of routers. Additionally, it explains the shortest path algorithm in networking and defines a socket as an endpoint for communication between programs.

Uploaded by

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

Question 7: Study different types of networking commands:

1. hostname 2. ipconfig or ifconfig 3. ping 4. nslookup 5. tracert


6.netstat 7.arp -a 8.systeminfo 9.route 10.pathping
11.getmac 12.net /netview 13.nbtstat 14.netshare

1. hostname
displays the name of the current host system. Only users with root user authority can set the host
name.

2. ipconfig or ifconfig
The ipconfig command is used to display information about your network configuration and refresh
DHCP and DNS Settings. By default, the ipconfig command displays your IP Address, Subnet Mask,
and default gateway.

3. ping
ping is the primary TCP/IP command used to troubleshoot connectivity, reachability, and name
resolution. Used without parameters, this command displays Help content. You can also use this
command to test both the computer name and the IP address of the computer.

4. nslookup
Nslookup (stands for “Name Server Lookup”) is a useful command for getting information from the
DNS server. It is a network administration tool for querying the Domain Name System (DNS) to
obtain domain name or IP address mapping or any other specific DNS record. It is also used to
troubleshoot DNS-related problems.

Page no.
5. tracert
In the Command Prompt window, type 'tracert' followed by the destination, either an IP
Address or a Domain Name, and press Enter. The command will return output indicating the
hops discovered and time (in milliseconds) for each hop.

6. netstat
The netstat command generates displays that show network status and protocol statistics. You can
display the status of TCP and UDP endpoints in table format, routing table information, and interface
information. netstat displays various types of network data depending on the command line option
selected.

7. arp -a
The arp command displays and modifies the Internet-to-adapter address translation tables used by the
Address in Networks and communication management. The arp command displays the current ARP
entry for the host specified by the HostName variable.

Page no.
8. systeminfo
Windows has a built-in command to check the system configuration. It's called systeminfo and, when
you run it, it shows you a long list of information about your computer. Open Command Prompt or
PowerShell, type systeminfo and press Enter.

9. route
In computing, route is a command used to view and manipulate the IP routing table in Unix-like and
Microsoft Windows operating systems and also in IBM OS/2 and ReactOS. Manual manipulation of
the routing table is characteristic of static routing.

10. pathping

Page no.
The PathPing command is a command-line network utility included in Windows NT operating
systems since Windows 2000 that combines the functionality of ping with that of tracert. It is used to
locate spots that have network latency and network loss.

11. getmac
Returns the media access control (MAC) address and list of network protocols associated with each
address for all network cards in each computer, either locally or across a network. This command is
particularly useful either when you want to enter the MAC address into a network analyzer, or when
you need to know what protocols are currently in use on each network adapter on a computer.

12.net / net view


The net Command Prompt command manages almost any aspect of a network and its settings,
including network shares, network print jobs, and network users.
Net view is used to show a list of computers and network devices on the network.

13.nbtstat
NetBIOS over TCP/IP (NetBT) protocol statistics, NetBIOS name tables for both the local computer
and remote computers, and the NetBIOS name cache. This command also allows a refresh of the
NetBIOS name cache and the names registered with Windows Internet Name Service (WINS). Used
without parameters, this command displays Help information.
This command is available only if the Internet Protocol (TCP/IP) protocol is installed as a component
in the properties of a network adapter in Network Connections.

Page no.
14.net share
Manages shared resources. Used without parameters, net share displays information about all of the
resources that are shared on the local computer. For each resource, the device name(s) or pathname(s)
and a descriptive comment are displayed.

ASSIGNMENT 3

Page no.
Question 8:Use Cisco packet tracer to
(i) Establish peer to peer network
(ii) Establish star topology
(iii) Establish mesh topology
(iv) Use of router

1. Establish peer to peer network


Creating a peer-to-peer network using packet tracer involves connecting two devices directly
without any intermediate networking devices such as switches or routers. Below are the steps to
develop a peer-to-peer network using Packet Tracer :-
1. Open Packet Tracer :- Launch the Cisco Packet Tracer application on your computer.
2. Create a New Empty Workspace :- Start by creating a new empty workspace where you will
design your network.
3. Select Devices :- From the device palette, select the devices you want to use for your peer-to-
peer network. Common choices include routers, switches, PCs, and laptops.
4. Place Devices :- Place the selected devices on the workspace area. For a peer-to-peer
network, you will need at least two devices.
5. Connect Devices :- Use straight-through copper crossover cables to connect the devices
directly. Click on the first device, then click on the interface (port) you want to use for the
connection. Drag the cable to the second device and connect it to the desired interface. Repeat
this step for all required connections.
6. Configure IP Addresses (if necessary) :- If you are using devices that require IP addresses,
such as routers or PCs, configure IP addresses on their interfaces. This step is essential for
devices to communicate with each other. To configure IP addresses: - Click on the device you
want to configure. - Enter the configuration mode (if applicable). - Navigate to the interface you
want to configure and assign an IP address and subnet mask.
7. Verify Connectivity :- After configuring the devices and connecting them, verify connectivity
between them by sending ping requests or using other network troubleshooting tools available
in Packet Tracer.
8. Simulation Mode (Optional) :- Packet Tracer provides a simulation mode where you can test
your networks behavior in real-time. You can use this mode to simulate network traffic and
observe how your peer-to-peer network operates under different conditions.
9. Save Your Project :- Once you are satisfied with the configuration and connectivity of your
peer-to peer network, save your project for future reference. By following these steps, we can
easily develop a peer-to-peer network using Packet Tracer and gain hands-on experience in
configuring and testing network connections.

2. Establish star topology

Page no.
A star topology is a topology for a Local Area Network (LAN) in which all nodes are individually
connected to a central connection point, like a hub or a switch. A star takes more cable than e.g. a
bus, but the benefit is that if a cable fails, only one node will be brought down.

Creating a star topology network in Packet Tracer involves connecting multiple devices to a
central networking device, such as a switch or hub, where all communication flows through.
Here are the steps to develop a star topology network using Packet Tracer :-
1. Open Packet Tracer :- Launch the Cisco Packet Tracer application on your computer.
2. Create a New Empty Workspace :- Start by creating a new empty workspace where you will
design your network.
3. Select Devices :- From the device palette, select the devices you want to use for your star
topology network. You will need at least one central networking device (e.g., a switch or a hub)
and multiple end devices (e.g., PCs or laptops).
4. Place Devices :- Place the selected devices on the workspace area. Position the central
networking device (switch or hub) at the center of the workspace, and arrange the end devices
(PCs or laptops) around it.
5. Connect Devices to the Central Device :- Use straight-through copper cables to connect each
end device to an available port on the central networking device. For example, if you are using a
switch, connect each PC or laptop to one of the switch’s ports. Drag the cable from the port on
the end device to an available port on the central networking device.
6. Configure IP Addresses (if necessary) :- If you are using devices that require IP addresses, such
as routers or PCs, configure IP addresses on their interfaces. This step is essential for devices to
communicate with each other. To configure IP addresses:
 Click on the device you want to configure.
 Enter the configuration mode (if applicable).
 Navigate to the interface you want to configure and assign an IP address and subnet mask.
7. Verify Connectivity :- After configuring the devices and connecting them to the central
networking device, verify connectivity between them by sending ping requests or using other
network troubleshooting tools available in Packet Tracer.
8. Simulation Mode (Optional) :- Packet Tracer provides a simulation mode where you can test
your networks behavior in real-time. You can use this mode to simulate network traffic and
observe how your star topology network operates under different conditions.
9. Save Your Project :- Once you are satisfied with the configuration and connectivity of your star
topology network, save your project for future reference. By following these steps, you can easily
develop a star topology network using Packet Tracer and gain hands-on experience in configuring
and testing network connections.
Using hub:

Page no.
Using switch:

3. Establish mesh topology


Mesh topology is a network configuration where devices are interconnected in a decentralized
manner. Instead of relying on a central hub or switch, each device connects directly to multiple
other devices, forming a mesh-like structure.

Creating a mesh network topology in Cisco can be achieved using devices such as routers or
switches. Here are the steps to simulate a mesh network topology in Cisco Packet Tracer, a
network simulation software :-
1. Open Cisco Packet Tracer :- Launch the Cisco Packet Tracer application on your computer.
2. Create Devices :- Place the required devices onto the workspace. You'll typically use routers or
switches to simulate a mesh network. You can find these devices in the device panel on the left
side of the interface.
3. Connect Devices :- Connect the devices together using appropriate cables. For a mesh
network, each device should be connected to every other device in the network. This means
you'll have multiple connections between devices.
4. Configure IP Addresses :- Assign IP addresses to the interfaces of each device. Ensure that
each device has a unique IP address within the same subnet. You can do this by accessing the
command-line interface (CLI) of each device and using commands such as interface and ip
address.
5. Configure Routing :- Set up routing protocols or static routes to ensure proper communication
between devices. Common routing protocols used in mesh networks include OSPF (Open
Shortest Path First) and EIGRP (Enhanced Interior Gateway Routing Protocol). Configure these
protocols on each device to enable dynamic routing.
6. Verify Connectivity :- After configuring the network, verify connectivity between devices. You
can do this by sending ping commands from one device to another and ensuring that packets are
successfully transmitted.
7. Test Redundancy :- Simulate failure scenarios to test the redundancy of the mesh network.
Disconnect links between devices or simulate device failures to observe how traffic reroutes
through alternate paths.
8. Monitor Network Performance :- Use monitoring tools available in Cisco Packet Tracer to
analyze network performance. This includes checking interface statistics, routing tables, and any
network errors or congestion.
9. Documentation :- Document the network topology, including device configurations, IP
addressing schemes, and routing protocols used. This documentation will be helpful for
troubleshooting and future reference. By following these steps, you can simulate a mesh

Page no.
network topology in Cisco Packet Tracer and gain insights into the behavior and performance of
such a network configuration.

4. Use of router
Simulating a router involves several steps, especially if youre looking to create a realistic model.
Heres a basic outline of the steps you might follow :-
1. Launch Packet Tracer :- Open the Cisco Packet Tracer application on your computer.

2. Model the Router Components :-


i. Physical Components :- Model the physical components of the router including the CPU,
memory, interfaces (Ethernet, serial, etc.), and the routing table.
ii. Operating System :- Model the operating system running on the router, typically some
variant of Cisco IOS or Juniper Junos.
iii. Routing Protocols :- Implement the routing protocols you want to simulate (e.g., OSPF,
BGP, RIP) and their associated algorithms for route computation and convergence.
iv. Packet Forwarding Logic :- Implement the logic for packet forwarding based on the
routing table entries and configured policies (e.g., access lists, NAT).
v. Quality Of Service (QOS) :- If needed, include mechanisms for QoS such as traffic shaping,
prioritization, and queuing.

3. Define the Network Topology :- Design the network topology in which the router will operate.
This includes specifying the connections to other routers, switches, and hosts, as well as the types of
links (e.g., Ethernet, serial) and their characteristics (bandwidth, delay, reliability).

4. Configure the Router :- Set up the routers initial configuration including IP addressing, routing
protocol parameters, interface settings, and any other relevant configurations.

5. Generate Traffic :- Generate traffic flows within the network to simulate real-world scenarios. This
may involve using traffic generators or scripting traffic patterns.

6. Run the Simulation :- Execute the simulation and observe the behavior of the router and the
network as a whole. Monitor metrics such as packet loss, latency, throughput, and routing table
updates.

7. Analyze Results :- Analyze the simulation results to evaluate the performance of the router and
the network under different conditions. This may involve comparing against expected outcomes or
benchmarks.

Page no.
8. Optimize and Iterate :- Based on the results of the simulation, refine the model, configurations, or
network topology as needed to improve performance or address any issues identified.

9. Document and Report Findings :- Document the simulation setup, methodology, results, and any
insights gained from the simulation. This information can be valuable for sharing findings with others
or for future reference. By following these steps, you can create a simulation of a router that
accurately represents its behavior in a network environment.

Page no.
ASSIGNMENT 4

Question 9:Demonstrate how shortest path algorithm is used in network?


Lets consider a simplified example with four routers labeled A, B, C, and D, interconnected as follows:
-> Router A is directly connected to routers B and C.
-> Router B is directly connected to routers A, C, and D.
-> Router C is directly connected to routers A, B, and D.
-> Router D is directly connected to routers B and C.
Now, lets assume Router A wants to send data packets to Router D. The routing algorithm, such as
OSPF or EIGRP, helps Router A determine the shortest path to reach Router D. Heres how it might
work:

1. Router As Routing Table: Router A maintains a routing table that contains information about the
available paths to different destinations. Initially, Router As routing table might look like this:
Destination Next Hop
---------------------------------
B B
C C

2. Sending the Packet: When Router A receives a packet destined for Router D, it consults its routing
table to determine the next hop. Since Router D is not directly connected to Router A, Router A
needs to forward the packet to another router that can get it closer to Router D.

3. Shortest Path Calculation: Router A uses a shortest path algorithm (like Dijkstras algorithm in
OSPF) to calculate the shortest path to Router D. In this example, the shortest path from Router A to
Router D is through Router B.

4. Updating the Routing Table: After calculating the shortest path, Router A updates its routing table:
Destination Next Hop
-----------------------------------
B B
C C
D B (Updated)
Now, Router A knows that to reach Router D, it should forward packets to Router B.

5. Forwarding the Packet: Router A forwards the packet to Router B, as Router B is the next hop on
the shortest path to Router D.

6. Next Hops Along the Path: Router B, upon receiving the packet, follows a similar process to
determine the next hop along the shortest path to Router D.
This continues until the packet reaches Router D. This process ensures that routers choose the
shortest path based on the metrics (such as cost, bandwidth, delay) configured in the routing
algorithm. OSPF and EIGRP are examples of routing protocols that use such algorithms to determine
optimal paths in a network.

Page no.
ASSIGNMENT 5

Question 10:Define Socket.


A socket is one endpoint of a two way communication link between two programs running on the
network. The socket mechanism provides a means of inter-process communication (IPC) by
establishing named contact points between which the communication take place.

Like ‘Pipe’ is used to create pipes and sockets is created using ‘socket’ system call. The socket
provides bidirectional FIFO Communication facility over the network. A socket connecting to the
network is created at each end of the communication. Each socket has a specific address. This address
is composed of an IP address and a port number.

Page no.
Socket are generally employed in client server applications. The server creates a socket, attaches it to
a network port addresses then waits for the client to contact it. The client creates a socket and then
attempts to connect to the server socket. When the connection is established, transfer of data takes
place.

Types of Sockets : There are two types of Sockets: the datagram socket and the stream socket.

1.Datagram Socket : This is a type of network which has connection less point for sending and
receiving packets. It is similar to mailbox. The letters (data) posted into the box are collected and
delivered (transmitted) to a letterbox (receiving socket).

2.Stream Socket: In Computer operating system, a stream socket is type of interprocess


communications socket or network socket which provides a connection-oriented, sequenced, and
unique flow of data without record boundaries with well defined mechanisms for creating and
destroying connections and for detecting errors. It is similar to phone. A connection is established
between the phones (two ends) and a conversation (transfer of data) takes place.

Function
Call Description

Socket() To create a socket

It’s a socket identification like a telephone number


Bind()
to contact

Listen() Ready to receive a connection

Connect() Ready to act as a sender

Page no.
Function
Call Description

Confirmation, it is like accepting to receive a call


Accept()
from a sender

Write() To send data

Read() To receive data

Close() To close a connection

Question 11:Explain Client Server Architecture.


The Client-server model is a distributed application structure that partitions tasks or workloads
between the providers of a resource or service, called servers, and service requesters called
clients. In the client-server architecture, when the client computer sends a request for data to
the server through the internet, the server accepts the requested process and delivers the data
packets requested back to the client.
 Client: When we say the word Client, it means to talk of a person or an organization using
a particular service. Similarly in the digital world, a Client is a computer (Host) i.e. capable
of receiving information or using a particular service from the service providers (Servers).

 Servers: Similarly, when we talk about the word Servers, It means a person or medium that
serves something. Similarly in this digital world, a Server is a remote computer that
provides information (data) or access to particular services.

Question 12:Explain different types of Socket.

1. Datagram Socket : This is a type of network which has connection less point for sending
and receiving packets. It is similar to mailbox. The letters (data) posted into the box are
collected and delivered (transmitted) to a letterbox (receiving socket).

Page no.
2. Stream Socket In Computer operating system, a stream socket is type of interprocess
communications socket or network socket which provides a connection-oriented, sequenced,
and unique flow of data without record boundaries with well defined mechanisms for
creating and destroying connections and for detecting errors. It is similar to phone. A
connection is established between the phones (two ends) and a conversation (transfer of
data) takes place.

ASSIGNMENT 6

Question 13:Write a datagram socket program for implementing echo server.

//Datagram Echo Client


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

Page no.
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}

//UDP ECHO Server


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

class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
//String capitalizedSentence = sentence.toUpperCase();
sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}

Page no.
Question 14:Write a datagram socket program for implementing Date-time server.

//Server-side Program:
import java.io.*;
import java.net.*;

public class DateTimeServer {


public static void main(String[] args) {
try {
// Create a DatagramSocket bound to port 12345
DatagramSocket serverSocket = new DatagramSocket(12345);
System.out.println("Server is running...");
while (true) {
// Create a buffer to store received data
byte[] receiveData = new byte[1024];
// Create a DatagramPacket to receive data from the client
DatagramPacket receivePacket = new DatagramPacket(receiveData
, receiveData.length);

// Receive data from the client


serverSocket.receive(receivePacket);

// Get the client's address and port


InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();

// Get the current date and time


String dateTime = java.time.LocalDateTime.now().toString();

// Convert the date and time to bytes


byte[] sendData = dateTime.getBytes();

// Create a DatagramPacket to send data to the client


DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, clientAddress, clientPort);

// Send the data to the client


serverSocket.send(sendPacket);

System.out.println("Date/time sent to client: " + dateTime);


}
} catch (IOException e) {
e.printStackTrace();
}
}
}

//Client-side Program:
import java.io.*;

Page no.
import java.net.*;
public class DateTimeClient {
public static void main(String[] args) {
try {
// Create a DatagramSocket
DatagramSocket clientSocket = new DatagramSocket();

// Specify the server's address and port


InetAddress serverAddress = InetAddress.getByName("localhost");
int serverPort = 12345;

// Create a buffer to store received data


byte[] receiveData = new byte[1024];

// Create a DatagramPacket to send data to the server


DatagramPacket sendPacket = new DatagramPacket(new byte[0], 0, serverAddress, serverPort);

// Send an empty packet to the server to request date/time


clientSocket.send(sendPacket);

// Create a DatagramPacket to receive data from the server


DatagramPacket receivePacket = new DatagramPacket(receiveData
, receiveData.length);

// Receive data from the server


clientSocket.receive(receivePacket);

// Convert the received data to a string


String dateTime = new String(receivePacket.getData(), 0, receivePacket.getLength());

// Print the received date/time


System.out.println("Received date/time from server: " + dateTime);

// Close the socket


clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

ASSIGNMENT 7

Question 13:Write a stream socket program for implementing echo server.

//Server-side Program:
import java.io.BufferedReader;
import java.io.IOException;

Page no.
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {


public static void main(String[] args) {
final int PORT_NUMBER = 1234;
try (ServerSocket serverSocket = new ServerSocket(PORT_NUMBER)) {
System.out.println("Echo Server is running on port " + PORT_NUMBER);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
// Start a new thread to handle the client
new Thread(new ClientHandler(clientSocket)).start();
}
} catch (IOException e) {
System.err.println("Error in the server: " + e.getMessage());
}
}
private static class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true)) {
String inputLine;
while ((inputLine = reader.readLine()) != null) {
System.out.println("Received from client: " + inputLine);
// Echo the input back to the client
writer.println(inputLine);
}
} catch (IOException e) {
System.err.println("Error handling client: " + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (IOException e) {
System.err.println("Error closing client socket: " + e.getMessage());
}
}
}
}
}

//Client-side Program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

Page no.
import java.io.PrintWriter;
import java.net.Socket;

public class EchoClient {


public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost";
final int PORT_NUMBER = 1234;
try (Socket socket = new Socket(SERVER_ADDRESS, PORT_NUMBER); BufferedReader reader =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); BufferedReader
userInputReader = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Connected to echo server at " + SERVER_ADDRESS + ":" + PORT_NUMBER);
System.out.println("Type 'exit' to quit.");
String userInput;
while ((userInput = userInputReader.readLine()) != null) {
if ("exit".equalsIgnoreCase(userInput.trim())) {
break;
}
// Send user input to the server
writer.println(userInput);
// Receive and print server's response
System.out.println("Server response: " + reader.readLine());
}
} catch (IOException e) {
System.err.println("Error in the client: " + e.getMessage());
}
}
}

Question 14:Write a stream socket program for implementing Date-time server.

//Server-side Program:
import java.io.*;
import java.net.*;
import java.util.*;

Page no.
public class DateTimeServer {
public static void main(String[] args) {
final int PORT = 12345; // Choose any available port number
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is running and waiting for client connections...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: "
+ clientSocket.getInetAddress().getHostAddress());
// Create output stream to send data to client
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// Get current date and time
Date currentDate = new Date();
// Send date/time string to client
out.println("Current Date and Time: " + currentDate);
// Close the connection
clientSocket.close();
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

//Client- side Program:


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

public class DateTimeClient {


public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost"; // Server address
final int SERVER_PORT = 12345; // Server port number

try (
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()))
){
// Read the date/time string from the server
String dateTime = in.readLine();
System.out.println("Received from server: " + dateTime);
} catch (UnknownHostException e) {
System.err.println("Error: Unknown host " + SERVER_ADDRESS);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Page no.
Page no.

You might also like