Notes
Notes
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/internet-module.h"
#include "ns3/network-module.h"
#include "ns3/netanim-module.h"
#include "ns3/mobility-module.h"
int main(){
LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);
NodeContainer nodeContainer;
nodeContainer.Create(2);
PointToPointHelper pointTopoint;
pointTopoint.SetDeviceAttribute("DataRate", StringValue("50Mbps"));
pointTopoint.SetChannelAttribute("Delay",StringValue("5ms"));
NetDeviceContainer devices;
devices = pointTopoint.Install(nodeContainer);
InternetStackHelper stack;
stack.Install(nodeContainer);
Ipv4AddressHelper address;
address.SetBase("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interface;
interface = address.Assign(devices);
ApplicationContainer serverApplications;
ApplicationContainer clientApplications;
//server
UdpEchoServerHelper server(9); //listening on port 9
//client
UdpEchoClientHelper client (interface.GetAddress(0), 9); //serverAddres, port
client.SetAttribute("MaxPackets", StringValue("100"));
client.SetAttribute("Interval", StringValue("1"));
client.SetAttribute("PacketSize", StringValue("1024"));
MobilityHelper mobility;
mobility.Install(nodeContainer);
Simulator::Run();
Simulator::Destroy();
return 0;
//Exam_Lan
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/internet-module.h"
#include "ns3/network-module.h"
#include "ns3/netanim-module.h"
#include "ns3/mobility-module.h"
#include "ns3/csma-module.h"
int main () {
LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);
// Assign IP addresses
Ipv4AddressHelper address;
address.SetBase("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer lan1Interfaces = address.Assign(lan1Devices);
address.SetBase("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer lan2Interfaces = address.Assign(lan2Devices);
address.SetBase("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer routerInterfaces = address.Assign(routerDevices);
ApplicationContainer clientApps;
clientApps.Add(echoClient.Install(lan1Nodes.Get(0))); // Client on LAN1
clientApps.Start(Seconds(2.0));
clientApps.Stop(Seconds(10.0));
// Set up Mobility
MobilityHelper mobility;
mobility.Install(lan1Nodes);
mobility.Install(lan2Nodes);
mobility.Install(routerNodes);
Simulator::Run();
Simulator::Destroy();
return 0;
}
exam_star
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/internet-module.h"
#include "ns3/network-module.h"
#include "ns3/netanim-module.h"
#include "ns3/mobility-module.h"
int main(){
LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);
NetDeviceContainer devices;
for (int i = 0; i < 4; i++) {
NetDeviceContainer device = pointToPoint.Install(hubNode.Get(0),
leafNodes.Get(i));
devices.Add(device); // Connect each leaf node to the hub
}
Ipv4AddressHelper address;
address.SetBase("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interface;
interface = address.Assign(devices);
ApplicationContainer serverApplications;
ApplicationContainer clientApplications;
// Mobility
MobilityHelper mobility;
mobility.Install(nodeContainer);
Simulator::Run();
Simulator::Destroy();
return 0;
}
exam_wifi
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/network-module.h"
#include "ns3/netanim-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/ssid.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("SimplifiedExample");
CommandLine cmd;
cmd.AddValue("nCsma", "Number of CSMA nodes", nCsma);
cmd.AddValue("nWifi", "Number of wifi STA devices", nWifi);
cmd.AddValue("verbose", "Enable logging", verbose);
cmd.AddValue("tracing", "Enable pcap tracing", tracing);
cmd.Parse(argc, argv);
if (verbose) {
LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO);
}
// Create nodes
NodeContainer p2pNodes;
p2pNodes.Create(2);
NodeContainer csmaNodes;
csmaNodes.Add(p2pNodes.Get(1));
csmaNodes.Create(nCsma);
NodeContainer wifiStaNodes;
wifiStaNodes.Create(nWifi);
// Set up Wi-Fi
YansWifiChannelHelper channel = YansWifiChannelHelper::Default();
YansWifiPhyHelper phy;
phy.SetChannel(channel.Create());
WifiHelper wifi;
WifiMacHelper mac;
Ssid ssid = Ssid("ns-3-ssid");
NetDeviceContainer staDevices;
mac.SetType("ns3::StaWifiMac", "Ssid", SsidValue(ssid));
staDevices = wifi.Install(phy, mac, wifiStaNodes);
NetDeviceContainer apDevices;
mac.SetType("ns3::ApWifiMac", "Ssid", SsidValue(ssid));
apDevices = wifi.Install(phy, mac, p2pNodes.Get(0));
// Set up mobility
MobilityHelper mobility;
mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
DoubleValue(0.0), "MinY", DoubleValue(0.0),
"DeltaX", DoubleValue(5.0), "DeltaY",
DoubleValue(10.0), "GridWidth", UintegerValue(3),
"LayoutType", StringValue("RowFirst"));
mobility.SetMobilityModel("ns3::RandomWalk2dMobilityModel", "Bounds",
RectangleValue(Rectangle(-50, 50, -50, 50)));
mobility.Install(wifiStaNodes);
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
mobility.Install(p2pNodes.Get(0));
Ipv4AddressHelper address;
address.SetBase("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer p2pInterfaces = address.Assign(p2pDevices);
address.SetBase("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer csmaInterfaces = address.Assign(csmaDevices);
address.SetBase("10.1.3.0", "255.255.255.0");
address.Assign(staDevices);
address.Assign(apDevices);
// Routing tables
Ipv4GlobalRoutingHelper::PopulateRoutingTables();
// NetAnim
AnimationInterface anim("wifi.xml");
// Run simulation
Simulator::Stop(Seconds(10.0));
if (tracing) {
phy.SetPcapDataLinkType(WifiPhyHelper::DLT_IEEE802_11_RADIO);
p2p.EnablePcapAll("simplified");
phy.EnablePcap("simplified", apDevices.Get(0));
csma.EnablePcap("simplified", csmaDevices.Get(0), true);
}
Simulator::Run();
Simulator::Destroy();
return 0;
}
exam_flow
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/flow-monitor-module.h"
CommandLine cmd;
cmd.AddValue("numClients", "Number of client nodes", numClients);
cmd.Parse(argc, argv);
NodeContainer clientNodes;
clientNodes.Create(numClients);
Simulator::Destroy();
return 0;
}
//exam_star_gnuPlot
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/internet-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/netanim-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("StarTopology");
void
PrintStats(Ptr<FlowMonitor> monitor, Ptr<Ipv4FlowClassifier> classifier)
{
FlowMonitor::FlowStatsContainer stats = monitor->GetFlowStats();
double totalThroughput = 0.0;
double totalPacketLoss = 0.0;
uint32_t flowCount = 0;
for (auto i : stats)
{
FlowId flowId = i.first;
FlowMonitor::FlowStats s = i.second;
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow(flowId);
std::cout << "Flow from " << t.sourceAddress << " to " <<
t.destinationAddress << std::endl;
std::cout << " Transmitted Bytes: " << s.txBytes << std::endl;
std::cout << " Received Bytes: " << s.rxBytes << std::endl;
std::cout << " Lost Packets: " << s.lostPackets << std::endl;
if (s.rxPackets > 0)
{
double delay = (s.delaySum.GetSeconds() * 1000 / s.rxPackets);
std::cout << " Average Delay (ms): " << delay << std::endl;
double throughput = (s.rxBytes * 8.0 /
s.timeLastRxPacket.GetSeconds() / 1000000.0);
std::cout << " Throughput (Mbps): " << throughput << std::endl;
totalThroughput += throughput;
flowCount++;
}
else
{
std::cout << " No packets received." << std::endl;
}
totalPacketLoss += s.lostPackets;
}
if (flowCount > 0)
{
std::cout << "Average Throughput (Mbps): " << (totalThroughput / flowCount)
<< std::endl;
}
else
{
std::cout << "No flows received any packets." << std::endl;
}
double averagePacketLoss = totalPacketLoss / stats.size();
std::cout << "Average Packet Loss: " << averagePacketLoss << " packets" <<
std::endl;
}
int
main(int argc, char* argv[])
{
uint32_t nNodes = 15;
CommandLine cmd(__FILE__);
cmd.AddValue("nNodes", "Number of peripheral nodes", nNodes);
cmd.Parse(argc, argv);
nNodes = std::max(nNodes, 2u);
NodeContainer centralNode;
centralNode.Create(1);
NodeContainer peripheralNodes;
peripheralNodes.Create(nNodes);
PointToPointHelper p2p;
p2p.SetDeviceAttribute("DataRate", StringValue("5000Mbps"));
p2p.SetChannelAttribute("Delay", TimeValue(MicroSeconds(5)));
NetDeviceContainer centralDevice, peripheralDevices[nNodes];
Ipv4InterfaceContainer peripheralInterfaces[nNodes];
InternetStackHelper stack;
stack.Install(centralNode);
stack.Install(peripheralNodes);
Ipv4AddressHelper address;
for (uint32_t i = 0; i < nNodes; ++i)
{
NodeContainer linkNodes = NodeContainer(centralNode.Get(0),
peripheralNodes.Get(i));
NetDeviceContainer linkDevices = p2p.Install(linkNodes);
std::ostringstream subnet;
subnet << "10.1." << i + 1 << ".0";
address.SetBase(subnet.str().c_str(), "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign(linkDevices);
centralDevice.Add(linkDevices.Get(0));
peripheralDevices[i].Add(linkDevices.Get(1));
peripheralInterfaces[i] = interfaces;
}
for (uint32_t i = 1; i < nNodes; i += 2)
{
UdpEchoServerHelper echoServer(1000 + i);
ApplicationContainer serverApps =
echoServer.Install(peripheralNodes.Get(i));
serverApps.Start(Seconds(1.0));
serverApps.Stop(Seconds(20.0));
}
for (uint32_t i = 0; i < nNodes; i += 2)
{
if (i + 1 < nNodes)
{
UdpEchoClientHelper echoClient(peripheralInterfaces[i +
1].GetAddress(1),
1000 + (i + 1));
echoClient.SetAttribute("MaxPackets", UintegerValue(10));
echoClient.SetAttribute("Interval", TimeValue(Seconds(.01)));
echoClient.SetAttribute("PacketSize", UintegerValue(1024));
ApplicationContainer clientApps =
echoClient.Install(peripheralNodes.Get(i));
clientApps.Start(Seconds(1.0));
clientApps.Stop(Seconds(20.0));
}
}
Ipv4GlobalRoutingHelper::PopulateRoutingTables();
FlowMonitorHelper flowMonitorHelper;
Ptr<FlowMonitor> monitor = flowMonitorHelper.InstallAll();
Ptr<Ipv4FlowClassifier> classifier =
DynamicCast<Ipv4FlowClassifier>(flowMonitorHelper.GetClassifier());
p2p.EnablePcapAll("star_topology_example");
AnimationInterface anim("star_topology_example.xml");
Simulator::Stop(Seconds(20.0));
Simulator::Run();
PrintStats(monitor, classifier);
Simulator::Destroy();
return 0;
}
//Exam_RING_GNU_PLOT
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/mobility-module.h"
#include "ns3/netanim-module.h"
#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("RING_TOPOLOGY");
int
main(int argc, char* argv[])
{
Config::SetDefault("ns3::OnOffApplication::PacketSize", UintegerValue(250));
Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("5kb/s"));
uint32_t N = 9;
CommandLine cmd(__FILE__);
cmd.AddValue("nNodes", "Number of clientNodes to place in the star", N);
cmd.Parse(argc, argv);
NS_LOG_INFO("Create clientNodes.");
NodeContainer serverNode;
NodeContainer clientNodes;
serverNode.Create(1);
clientNodes.Create(N - 1);
NodeContainer allNodes = NodeContainer(serverNode, clientNodes);
InternetStackHelper internet;
internet.Install(allNodes);
std::vector<NodeContainer> nodeAdjacencyList(N - 1);
for (uint32_t i = 0; i < nodeAdjacencyList.size(); ++i)
{
nodeAdjacencyList[i] = NodeContainer(serverNode, clientNodes.Get(i));
}
NS_LOG_INFO("Create channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
p2p.SetChannelAttribute("Delay", StringValue("2ms"));
std::vector<NetDeviceContainer> deviceAdjacencyList(N - 1);
for (uint32_t i = 0; i < deviceAdjacencyList.size(); ++i)
{
deviceAdjacencyList[i] = p2p.Install(nodeAdjacencyList[i]);
}
NS_LOG_INFO("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
std::vector<Ipv4InterfaceContainer> interfaceAdjacencyList(N - 1);
for (uint32_t i = 0; i < interfaceAdjacencyList.size(); ++i)
{
std::ostringstream subnet;
subnet << "10.1." << i + 1 << ".0";
ipv4.SetBase(subnet.str().c_str(), "255.255.255.0");
interfaceAdjacencyList[i] = ipv4.Assign(deviceAdjacencyList[i]);
}
Ipv4GlobalRoutingHelper::PopulateRoutingTables();
uint16_t port = 50000;
Address sinkLocalAddress(InetSocketAddress(Ipv4Address::GetAny(), port));
PacketSinkHelper sinkHelper("ns3::TcpSocketFactory", sinkLocalAddress);
ApplicationContainer sinkApp = sinkHelper.Install(serverNode);
sinkApp.Start(Seconds(1.0));
sinkApp.Stop(Seconds(10.0));
OnOffHelper clientHelper("ns3::TcpSocketFactory", Address());
clientHelper.SetAttribute("OnTime",
StringValue("ns3::ConstantRandomVariable[Constant=1]"));
clientHelper.SetAttribute("OffTime",
StringValue("ns3::ConstantRandomVariable[Constant=0]"));
ApplicationContainer clientApps;
for (uint32_t i = 0; i < clientNodes.GetN(); ++i)
{
AddressValue remoteAddress(
InetSocketAddress(interfaceAdjacencyList[i].GetAddress(0), port));
clientHelper.SetAttribute("Remote", remoteAddress);
clientApps.Add(clientHelper.Install(clientNodes.Get(i)));
}
clientApps.Start(Seconds(1.0));
clientApps.Stop(Seconds(10.0));
// configure tracing
AsciiTraceHelper ascii;
p2p.EnablePcapAll("tcp-star-server");
NS_LOG_INFO("Run Simulation.");
MobilityHelper mobility;
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
mobility.Install(allNodes);
AnimationInterface anim("second_script.xml");
for (uint32_t i = 0; i < clientNodes.GetN(); ++i) {
anim.SetConstantPosition(clientNodes.Get(i), i * 3, 0.0);
}
anim.SetConstantPosition(serverNode.Get(0), 11.0, 22.0);
Simulator::Run();
Simulator::Destroy();
NS_LOG_INFO("Done.");
return 0; }
//Exam_HYBRID_GNU_PLOT
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/network-module.h"
#include "ns3/netanim-module.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/point-to-point-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("HybridTopology");
void PrintStats(Ptr<FlowMonitor> monitor, Ptr<Ipv4FlowClassifier>
classifier) {
FlowMonitor::FlowStatsContainer stats = monitor->GetFlowStats();
double totalThroughput = 0.0;
double totalPacketLoss = 0.0;
uint32_t flowCount = 0;
for (auto i : stats) {
FlowId flowId = i.first;
FlowMonitor::FlowStats s = i.second;
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow(flowId);
std::cout << "Flow from " << t.sourceAddress << " to " <<
t.destinationAddress << std::endl;
std::cout << " Transmitted Bytes: " << s.txBytes << std::endl;
std::cout << " Received Bytes: " << s.rxBytes << std::endl;
std::cout << " Lost Packets: " << s.lostPackets << std::endl;
if (s.rxPackets > 0) {
double delay = (s.delaySum.GetSeconds() * 1000 / s.rxPackets);
std::cout << " Average Delay (ms): " << delay << std::endl;
double throughput = (s.rxBytes * 8.0 / s.timeLastRxPacket.GetSeconds() /
1000000.0);
std::cout << " Throughput (Mbps): " << throughput << std::endl;
totalThroughput += throughput;
flowCount++;
} else {
std::cout << " No packets received." << std::endl;
}
totalPacketLoss += s.lostPackets;
}
if (flowCount > 0) {
//Exam_TCP_Tahoe
#include "tutorial-app.h"
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include <fstream>
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("FifthScriptExample");
//
========================================================================
===
//
// node 0 node 1
// +----------------+ +----------------+
// | ns-3 TCP | | ns-3 TCP |
// +----------------+ +----------------+
// | 10.1.1.1 | | 10.1.1.2 |
// +----------------+ +----------------+
// | point-to-point | | point-to-point |
// +----------------+ +----------------+
// | |
// +---------------------+
// 5 Mbps, 2 ms
//
//
// We want to look at changes in the ns-3 TCP congestion window. We need
// to crank up a flow and hook the CongestionWindow attribute on the socket
// of the sender. Normally one would use an on-off application to generate a
// flow, but this has a couple of problems. First, the socket of the on-off
// application is not created until Application Start time, so we wouldn't be
// able to hook the socket (now) at configuration time. Second, even if we
// could arrange a call after start time, the socket is not public so we
// couldn't get at it.
//
// So, we can cook up a simple version of the on-off application that does what
// we want. On the plus side we don't need all of the complexity of the on-off
// application. On the minus side, we don't have a helper, so we have to get
// a little more involved in the details, but this is trivial.
//
// So first, we create a socket and do the trace connect on it; then we pass
// this socket into the constructor of our simple application which we then
// install in the source node.
//
========================================================================
===
//
/**
* Congestion window change callback
*
* \param oldCwnd Old congestion window.
* \param newCwnd New congestion window.
*/
static void
CwndChange(uint32_t oldCwnd, uint32_t newCwnd)
{
NS_LOG_UNCOND(Simulator::Now().GetSeconds() << "\t" << newCwnd);
}
/**
* Rx drop callback
*
* \param p The dropped packet.
*/
static void
RxDrop(Ptr<const Packet> p)
{
NS_LOG_UNCOND("RxDrop at " << Simulator::Now().GetSeconds());
}
int
main(int argc, char* argv[])
{
CommandLine cmd(__FILE__);
cmd.Parse(argc, argv);
// In the following three lines, TCP NewReno is used as the congestion
// control algorithm, the initial congestion window of a TCP connection is
// set to 1 packet, and the classic fast recovery algorithm is used. Note
// that this configuration is used only to demonstrate how TCP parameters
// can be configured in ns-3. Otherwise, it is recommended to use the default
// settings of TCP in ns-3.
Config::SetDefault("ns3::TcpL4Protocol::SocketType",
StringValue("ns3::TcpNewReno"));
Config::SetDefault("ns3::TcpSocket::InitialCwnd", UintegerValue(1));
Config::SetDefault("ns3::TcpL4Protocol::RecoveryType",
TypeIdValue(TypeId::LookupByName("ns3::TcpClassicRecovery")));
NodeContainer nodes;
nodes.Create(2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
pointToPoint.SetChannelAttribute("Delay", StringValue("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install(nodes);
Ptr<RateErrorModel> em = CreateObject<RateErrorModel>();
em->SetAttribute("ErrorRate", DoubleValue(0.00001));
devices.Get(1)->SetAttribute("ReceiveErrorModel", PointerValue(em));
InternetStackHelper stack;
stack.Install(nodes);
Ipv4AddressHelper address;
address.SetBase("10.1.1.0", "255.255.255.252");
Ipv4InterfaceContainer interfaces = address.Assign(devices);
uint16_t sinkPort = 8080;
Address sinkAddress(InetSocketAddress(interfaces.GetAddress(1), sinkPort));
PacketSinkHelper packetSinkHelper("ns3::TcpSocketFactory",
InetSocketAddress(Ipv4Address::GetAny(), sinkPort));
ApplicationContainer sinkApps = packetSinkHelper.Install(nodes.Get(1));
sinkApps.Start(Seconds(0.));
sinkApps.Stop(Seconds(20.));
Ptr<Socket> ns3TcpSocket = Socket::CreateSocket(nodes.Get(0),
TcpSocketFactory::GetTypeId());
ns3TcpSocket->TraceConnectWithoutContext("CongestionWindow",
MakeCallback(&CwndChange));
Ptr<TutorialApp> app = CreateObject<TutorialApp>();
app->Setup(ns3TcpSocket, sinkAddress, 1040, 1000, DataRate("1Mbps"));
nodes.Get(0)->AddApplication(app);
app->SetStartTime(Seconds(1.));
app->SetStopTime(Seconds(20.));
devices.Get(1)->TraceConnectWithoutContext("PhyRxDrop", MakeCallback(&RxDrop));
Simulator::Stop(Seconds(20));
Simulator::Run();
Simulator::Destroy();
return 0;
}
//Exam_TCP_RENO
#include "tutorial-app.h"
#include "ns3/applications-module.h"
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/stats-module.h"
#include <fstream>
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("SeventhScriptExample");
//
========================================================================
===
//
// node 0 node 1
// +----------------+ +----------------+
// | ns-3 TCP | | ns-3 TCP |
// +----------------+ +----------------+
// | 10.1.1.1 | | 10.1.1.2 |
// +----------------+ +----------------+
// | point-to-point | | point-to-point |
// +----------------+ +----------------+
// | |
// +---------------------+
// 5 Mbps, 2 ms
//
//
// We want to look at changes in the ns-3 TCP congestion window. We need
// to crank up a flow and hook the CongestionWindow attribute on the socket
// of the sender. Normally one would use an on-off application to generate a
// flow, but this has a couple of problems. First, the socket of the on-off
// application is not created until Application Start time, so we wouldn't be
// able to hook the socket (now) at configuration time. Second, even if we
// could arrange a call after start time, the socket is not public so we
// couldn't get at it.
//
// So, we can cook up a simple version of the on-off application that does what
// we want. On the plus side we don't need all of the complexity of the on-off
// application. On the minus side, we don't have a helper, so we have to get
// a little more involved in the details, but this is trivial.
//
// So first, we create a socket and do the trace connect on it; then we pass
// this socket into the constructor of our simple application which we then
// install in the source node.
//
// NOTE: If this example gets modified, do not forget to update the .png figure
// in src/stats/docs/seventh-packet-byte-count.png
//
========================================================================
===
//
/**
* Congestion window change callback
*
* \param stream The output stream file.
* \param oldCwnd Old congestion window.
* \param newCwnd New congestion window.
*/
static void
CwndChange(Ptr<OutputStreamWrapper> stream, uint32_t oldCwnd, uint32_t newCwnd)
{
NS_LOG_UNCOND(Simulator::Now().GetSeconds() << "\t" << newCwnd);
*stream->GetStream() << Simulator::Now().GetSeconds() << "\t" << oldCwnd << "\t" <<
newCwnd
<< std::endl;
}
/**
* Rx drop callback
*
* \param file The output PCAP file.
* \param p The dropped packet.
*/
static void
RxDrop(Ptr<PcapFileWrapper> file, Ptr<const Packet> p)
{
NS_LOG_UNCOND("RxDrop at " << Simulator::Now().GetSeconds());
file->Write(Simulator::Now(), p);
}
int
main(int argc, char* argv[])
{
bool useV6 = false;
CommandLine cmd(__FILE__);
cmd.AddValue("useIpv6", "Use Ipv6", useV6);
cmd.Parse(argc, argv);
NodeContainer nodes;
nodes.Create(2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
pointToPoint.SetChannelAttribute("Delay", StringValue("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install(nodes);
Ptr<RateErrorModel> em = CreateObject<RateErrorModel>();
em->SetAttribute("ErrorRate", DoubleValue(0.00001));
devices.Get(1)->SetAttribute("ReceiveErrorModel", PointerValue(em));
InternetStackHelper stack;
stack.Install(nodes);
uint16_t sinkPort = 8080;
Address sinkAddress;
Address anyAddress;
std::string probeType;
std::string tracePath;
if (!useV6)
{
Ipv4AddressHelper address;
address.SetBase("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign(devices);
sinkAddress = InetSocketAddress(interfaces.GetAddress(1), sinkPort);
anyAddress = InetSocketAddress(Ipv4Address::GetAny(), sinkPort);
probeType = "ns3::Ipv4PacketProbe";
tracePath = "/NodeList/*/$ns3::Ipv4L3Protocol/Tx";
}
else
{
Ipv6AddressHelper address;
address.SetBase("2001:0000:f00d:cafe::", Ipv6Prefix(64));
Ipv6InterfaceContainer interfaces = address.Assign(devices);
sinkAddress = Inet6SocketAddress(interfaces.GetAddress(1, 1), sinkPort);
anyAddress = Inet6SocketAddress(Ipv6Address::GetAny(), sinkPort);
probeType = "ns3::Ipv6PacketProbe";
tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx";
}
PacketSinkHelper packetSinkHelper("ns3::TcpSocketFactory", anyAddress);
ApplicationContainer sinkApps = packetSinkHelper.Install(nodes.Get(1));
sinkApps.Start(Seconds(0.));
sinkApps.Stop(Seconds(20.));
Ptr<Socket> ns3TcpSocket = Socket::CreateSocket(nodes.Get(0),
TcpSocketFactory::GetTypeId());
Ptr<TutorialApp> app = CreateObject<TutorialApp>();
app->Setup(ns3TcpSocket, sinkAddress, 1040, 1000, DataRate("1Mbps"));
nodes.Get(0)->AddApplication(app);
app->SetStartTime(Seconds(1.));
app->SetStopTime(Seconds(20.));
AsciiTraceHelper asciiTraceHelper;
Ptr<OutputStreamWrapper> stream =
asciiTraceHelper.CreateFileStream("seventh.cwnd");
ns3TcpSocket->TraceConnectWithoutContext("CongestionWindow",
MakeBoundCallback(&CwndChange, stream));
PcapHelper pcapHelper;
Ptr<PcapFileWrapper> file =
pcapHelper.CreateFile("seventh.pcap", std::ios::out, PcapHelper::DLT_PPP);
devices.Get(1)->TraceConnectWithoutContext("PhyRxDrop", MakeBoundCallback(&RxDrop,
file));
// Use GnuplotHelper to plot the packet byte count over time
GnuplotHelper plotHelper;
// Configure the plot. The first argument is the file name prefix
// for the output files generated. The second, third, and fourth
// arguments are, respectively, the plot title, x-axis, and y-axis labels
plotHelper.ConfigurePlot("seventh-packet-byte-count",
"Packet Byte Count vs. Time",
"Time (Seconds)",
"Packet Byte Count");
// Specify the probe type, trace source path (in configuration namespace), and
// probe output trace source ("OutputBytes") to plot. The fourth argument
// specifies the name of the data series label on the plot. The last
// argument formats the plot by specifying where the key should be placed.
plotHelper.PlotProbe(probeType,
tracePath,
"OutputBytes",
"Packet Byte Count",
GnuplotAggregator::KEY_BELOW);
// Use FileHelper to write out the packet byte count over time
FileHelper fileHelper;
// Configure the file to be written, and the formatting of output data.
fileHelper.ConfigureFile("seventh-packet-byte-count", FileAggregator::FORMATTED);
// Set the labels for this formatted output file.
fileHelper.Set2dFormat("Time (Seconds) = %.3e\tPacket Byte Count = %.0f");
// Specify the probe type, trace source path (in configuration namespace), and
// probe output trace source ("OutputBytes") to write.
fileHelper.WriteProbe(probeType, tracePath, "OutputBytes");
Simulator::Stop(Seconds(20));
Simulator::Run();
Simulator::Destroy();
return 0;
}
seventh.plt
set terminal png
set output "seventh-cwnd.png"
set title "Congestion-window vs. Time"
set xlabel "Time (Seconds)"
set ylabel "Congestion-window (Bytes)"
set datafile missing "-nan"
plot "seventh.cwnd" index 0 title "time" with linespoints, "seventh.cwnd" index 1
title "cwnd" with
linespoints
///----------------------------------------------
SOCKET----------------------------------------------///
//TCP_Client
#include <iostream>
#include <bits/stdc++.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
#define PORT 8081
#define BUFFER_SIZE 1024
int main() {
int clientFD = 0;
struct sockaddr_in serverAddress;
char buffer[BUFFER_SIZE] = {0};
// Creating socket file descriptor
if ((clientFD = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout<<"Socket creation error"<<endl;
return -1;
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr) <= 0) {
cout << "Invalid address / Address not supported" << endl;
return -1;
}
// Connect to the server
if (connect(clientFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) <
0) {
cout<< "Connection Failed" << endl;
return -1;
}
// Send a message to the server
const char *message = "Hello from client";
send(clientFD, message, strlen(message), 0);
cout << "Message sent to server" << endl;
// Read the acknowledgment message from the server
int valread = read(clientFD, buffer, BUFFER_SIZE);
cout << "Acknowledgment received from server: " << buffer << endl;
// Close the socket
close(clientFD);
return 0;
}
//TCP_SERVER
#include <iostream>
#include <bits/stdc++.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
#define PORT 8081
#define BUFFER_SIZE 1024
int main() {
int serverFD, newSocket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
// Creating socket file descriptor
if ((serverFD = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout<<"Socket Failed"<<endl;
exit(1);
}
// Forcefully attaching socket to the port 8081
if (setsockopt(serverFD, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,
sizeof(opt))) {
cout<<"Couldn't bind socket to port"<<endl;
exit(1);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT); //host to network short
// Binding the socket to the network address and port
if (bind(serverFD, (struct sockaddr *)&address, sizeof(address)) < 0) {
cout<<"Bind Failed"<<endl;
exit(1);
}
// Start listening for incoming connections
if (listen(serverFD, 3) < 0) {
cout<<"Client Connections overloaded"<<endl;
exit(1);
}
cout << "Server is listening on port " << PORT << endl;
// Accept an incoming connection
if ((newSocket = accept(serverFD, (struct sockaddr *)&address,
(socklen_t*)&addrlen)) < 0) {
cout<<"Error in accepting connection"<<endl;
exit(1);
}
// Read the message from the client
int valread = read(newSocket, buffer, BUFFER_SIZE);
cout << "Message received: " << buffer << endl;
// Send an acknowledgment message back to the client
const char *ackMessage = "Message received by server";
send(newSocket, ackMessage, strlen(ackMessage), 0);
cout << "Acknowledgment sent to client" << endl;
// Close the socket
close(newSocket);
close(serverFD);
return 0;
}
//UDP_Client
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <bits/stdc++.h>
using namespace std;
#define PORT 5566
#define BUFFER_SIZE 1024
int main() {
const char* ip = "127.0.0.1";
int clientFD;
struct sockaddr_in serverAddress;
socklen_t addressSize;
char buffer[BUFFER_SIZE];
// Create UDP socket
clientFD = socket(AF_INET, SOCK_DGRAM, 0);
if (clientFD < 0) {
cout<< "[-]Socket error" << endl;
return 1;
}
cout << "[+]UDP client socket created." << endl;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(PORT);
serverAddress.sin_addr.s_addr = inet_addr(ip);
addressSize = sizeof(serverAddress);
// Send message to server
cout << "Enter a message: ";
cin.getline(buffer, BUFFER_SIZE);
sendto(clientFD, buffer, strlen(buffer), 0, (struct sockaddr*)&serverAddress,
addressSize);
cout << "Message sent to server." << endl;
// Receive response from server
memset(buffer, 0, BUFFER_SIZE);
int n = recvfrom(clientFD, buffer, BUFFER_SIZE, 0, (struct
sockaddr*)&serverAddress,
&addressSize);
if (n < 0) {
cout<< "[-]Receive error" << endl;
close(clientFD);
return 1;
}
cout << "Server: " << buffer << endl;
close(clientFD);
return 0;}
//UPD_Server
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <bits/stdc++.h>
using namespace std;
#define PORT 5566
#define BUFFER_SIZE 1024
int main() {
int serverFD;
struct sockaddr_in serverAddress, clientAddress;
socklen_t addressSize;
char buffer[BUFFER_SIZE];
// Create UDP socket
serverFD = socket(AF_INET, SOCK_DGRAM, 0);
if (serverFD < 0) {
cout<< "[-]Socket error" << endl;
return 1;
}
cout << "[+]UDP server socket created." << endl;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(PORT);
serverAddress.sin_addr.s_addr = INADDR_ANY;
// Bind socket to address
if (bind(serverFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) {
cout<< "[-]Bind error" << endl;
close(serverFD);
return 1;
}
cout << "[+]Bind to the port number: " << PORT << endl;
while (true) {
addressSize = sizeof(clientAddress);
memset(buffer, 0, BUFFER_SIZE);
// Receive message from client
int n = recvfrom(serverFD, buffer, BUFFER_SIZE, 0, (struct
sockaddr*)&clientAddress,
&addressSize);
if (n < 0) {
cout << "[-]Receive error" << endl;
continue;
}
cout << "Client: " << buffer << endl;
// Send response to client
strcpy(buffer, "Hi, I am server!");
sendto(serverFD, buffer, strlen(buffer), 0, (struct sockaddr*)&clientAddress,
addressSize);
cout << "Server: " << buffer << endl;
}
close(serverFD);
return 0;}
//TCP_2_server_secondary
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <bits/stdc++.h>
using namespace std;
int main() {
int serverFD, client1_socket, client2_socket;
struct sockaddr_in serverAddress, client1Address, client2Address;
socklen_t addr_size1, addr_size2;
char buffer[1024];
// Create socket
serverFD = socket(AF_INET, SOCK_STREAM, 0);
if (serverFD < 0) {
cout << "Error creating socket." << endl;
return 1;
}
// Set server address
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345);
serverAddress.sin_addr.s_addr = INADDR_ANY;
memset(serverAddress.sin_zero, '\0', sizeof(serverAddress.sin_zero));
// Bind socket
if (bind(serverFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) {
cout<< "Error binding socket." << endl;
return 1;
}
// Listen for connections
if (listen(serverFD, 1) < 0) {
cout << "Error listening on socket." << endl;
return 1;
}
// accept
addr_size1 = sizeof(client1Address);
client1_socket = accept(serverFD, (struct sockaddr*)&client1Address, &addr_size1);
if (client1_socket < 0) {
cout<< "Error accepting connection from Client 1." << endl;
return 1;
}
// Receive character from Client 1
recv(client1_socket, buffer, 1024, 0);
char ch = buffer[0];
char prev = ch - 1;
close(client1_socket);
cout << "Character Received from Client-1 was decremented and sent to Client-2
successfully!" << endl;
addr_size2 = sizeof(client2Address);
client2_socket = accept(serverFD, (struct sockaddr*)&client2Address, &addr_size2);
if (client2_socket < 0) {
cout << "Error accepting connection from Client 2." << endl;
return 1;
}
// Send decremented character to Client 2
send(client2_socket, &prev, 1, 0);
close(client2_socket);
close(serverFD);
return 0;}
//TCP_Client1
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <bits/stdc++.h>
using namespace std;
int main() {
int client_socket;
struct sockaddr_in server_addr;
char buffer[1024];
// Create socket
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0) {
cout<< "Error creating socket." << endl;
return 1;
}
// Set server address
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(12345);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));
// Connect to server
if (connect(client_socket, (struct sockaddr*)&server_addr,
sizeof(server_addr)) < 0) {
cout<< "Error connecting to server." << endl;
return 1;
}
// Send character to server
cout << "Enter a character: ";
cin >> buffer[0];
send(client_socket, buffer, 1, 0);
cout << buffer[0] << " was sent to the server successfully!" << endl;
close(client_socket);
return 0;
}
//TCP_Client2
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <bits/stdc++.h>
using namespace std;
int main() {
int client_socket;
struct sockaddr_in server_addr;
char buffer[1024];
// Create socket
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0) {
cout<< "Error creating socket." << endl;
return 1;
}
// Set server address
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(12345);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));
// Connect to server
if (connect(client_socket, (struct sockaddr*)&server_addr,
sizeof(server_addr)) < 0) {
cout<< "Error connecting to server." << endl;
return 1;
}
// Receive character from server
recv(client_socket, buffer, 1024, 0);
cout << "Character received from server: " << buffer[0] << endl;
close(client_socket);
return 0;
}
///MATH_CLIENT_SERVER
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
#define PORT 4004
#define BUFFER_SIZE 50
int main(){
struct sockaddr_in serverAddress;
char buffer[BUFFER_SIZE] ={0};
char message[BUFFER_SIZE]={0};
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket<0){
cout<<"Socket failed"<<endl;
exit(EXIT_FAILURE);
}
serverAddress.sin_family=AF_INET;
serverAddress.sin_port = htons(PORT);
int convertX = inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr);
if(convertX<0){
cout<<"Conversion of address failed"<<endl;
exit(EXIT_FAILURE);
}
int connectX = connect(clientSocket,(struct sockaddr*)&serverAddress,
sizeof(serverAddress));
if(connectX<0){
cout<<"Connecting clientSocket to server failed"<<endl;
close(clientSocket);
exit(EXIT_FAILURE);
}
string exp;
cout<<"Enter the math expression: ";
cin>>exp;
for(int i=0;i<exp.size();i++) message[i] = exp[i];
send(clientSocket, message, strlen(message),0);
cout<<"Message sent to server!"<<endl;
int valread= read(clientSocket, buffer, BUFFER_SIZE);
cout<<"Server: "<<buffer<<endl;
close(clientSocket);
return 0;
}
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
#define PORT 4004
#define BUFFER_SIZE 50
int main()
{
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
int serverFD = socket(AF_INET, SOCK_STREAM, 0);
if (serverFD < 0)
{
cout << "Socket Creation failed" << endl;
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_port = htons(PORT);
address.sin_addr.s_addr = INADDR_ANY;
int bindX = bind(serverFD, (struct sockaddr *)&address, sizeof(address));
if (bindX < 0)
{
cout << "Bind failed" << endl;
exit(EXIT_FAILURE);
}
int listenX = listen(serverFD, 3);
if (listenX < 0)
{
cout << "Listen Failed" << endl;
exit(EXIT_FAILURE);
}
int newSocket = 0;
while (1)
{
newSocket = accept(serverFD, (struct sockaddr *)&address, (socklen_t
*)&addrlen);
if (newSocket < 0)
{
cout << "Accept Failed" << endl;
exit(EXIT_FAILURE);
}
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
#define PORT 4002
#define BUFFER_SIZE 50
int main(){
struct sockaddr_in serverAddress;
char buffer[BUFFER_SIZE] ={0};
char message[BUFFER_SIZE]={0};
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket<0){
cout<<"Socket failed"<<endl;
exit(EXIT_FAILURE);
}
serverAddress.sin_family=AF_INET;
serverAddress.sin_port = htons(PORT);
int convertX = inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr);
if(convertX<0){
cout<<"Conversion of address failed"<<endl;
exit(EXIT_FAILURE);
}
int connectX = connect(clientSocket,(struct sockaddr*)&serverAddress,
sizeof(serverAddress));
if(connectX<0){
cout<<"Connecting clientSocket to server failed"<<endl;
close(clientSocket);
exit(EXIT_FAILURE);
}
string exp;
cout<<"Enter expression: ";
cin>>exp;
for(int i=0;i<exp.size();i++) message[i] = exp[i];
send(clientSocket, message, strlen(message),0);
cout<<"Message sent to server!"<<endl;
int valread= read(clientSocket, buffer, BUFFER_SIZE);
cout<<"Server: "<<buffer<<endl;
close(clientSocket);
return 0; }
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
#define PORT 4002
#define BUFFER_SIZE 50
int main(){
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE]={0};
//SOCKET
int serverFD=socket(AF_INET, SOCK_STREAM, 0);
if(serverFD<0){
cout<<"Socket Creation failed"<<endl;
exit(EXIT_FAILURE);
}
address.sin_family=AF_INET;
address.sin_port=htons(PORT);
address.sin_addr.s_addr = INADDR_ANY;
int bindX = bind(serverFD, (struct sockaddr*)&address, sizeof(address));
if(bindX<0){
cout<<"Bind failed"<<endl;
exit(EXIT_FAILURE);
}
int listenX = listen(serverFD, 3);
if(listenX<0){
cout<<"Listen Failed"<<endl;
exit(EXIT_FAILURE);
}
int newSocket = accept(serverFD,(struct sockaddr*)&address,
(socklen_t*)&addrlen);
if(newSocket<0){
cout<<"Accept Failed"<<endl;
exit(EXIT_FAILURE);
}
int valread = read(newSocket, buffer, BUFFER_SIZE);
stack<int> s;
for(char i: buffer)
{
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
#define PORT 4003
#define BUFFER_SIZE 50
int main(){
struct sockaddr_in serverAddress;
char buffer[BUFFER_SIZE] ={0};
char message[BUFFER_SIZE]={0};
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket<0){
cout<<"Socket failed"<<endl;
exit(EXIT_FAILURE);
}
serverAddress.sin_family=AF_INET;
serverAddress.sin_port = htons(PORT);
int convertX = inet_pton(AF_INET, "127.0.0.1", &serverAddress.sin_addr);
if(convertX<0){
cout<<"Conversion of address failed"<<endl;
exit(EXIT_FAILURE);
}
int connectX = connect(clientSocket,(struct sockaddr*)&serverAddress,
sizeof(serverAddress));
if(connectX<0){
cout<<"Connecting clientSocket to server failed"<<endl;
close(clientSocket);
exit(EXIT_FAILURE);
}
string exp;
cout<<"Enter the string: ";
cin>>exp;
for(int i=0;i<exp.size();i++) message[i] = exp[i];
send(clientSocket, message, strlen(message),0);
cout<<"Message sent to server!"<<endl;
int valread= read(clientSocket, buffer, BUFFER_SIZE);
cout<<"Server: "<<buffer<<endl;
close(clientSocket);
return 0;
}
//Case Server Program
#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
#define PORT 4003
#define BUFFER_SIZE 50
int main(){
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE]={0};
//SOCKET
int serverFD=socket(AF_INET, SOCK_STREAM, 0);
if(serverFD<0){
cout<<"Socket Creation failed"<<endl;
exit(EXIT_FAILURE);
}
address.sin_family=AF_INET;
address.sin_port=htons(PORT);
address.sin_addr.s_addr = INADDR_ANY;
//BIND
int bindX = bind(serverFD, (struct sockaddr*)&address, sizeof(address));
if(bindX<0){
cout<<"Bind failed"<<endl;
exit(EXIT_FAILURE);
}
//LISTEN
int listenX = listen(serverFD, 3);
if(listenX<0){
cout<<"Listen Failed"<<endl;
exit(EXIT_FAILURE);
}
//ACCEPT
int newSocket = accept(serverFD,(struct sockaddr*)&address,
(socklen_t*)&addrlen);
if(newSocket<0){
cout<<"Accept Failed"<<endl;
exit(EXIT_FAILURE);
}
//READ
int valread = read(newSocket, buffer, BUFFER_SIZE);
//PROCESS
char message[BUFFER_SIZE]={0};
int j =0;
for(char ch : buffer){
if(ch>='a' && ch<='z'){
message[j]=toupper(ch);
j++;
}else if(ch>='A' && ch<='Z'){
message[j]=tolower(ch);
j++;
}else{
message[j]=ch;
j++;
}
}
//END PROCESSING..
//SEND
send(newSocket, &message, BUFFER_SIZE,0);
cout<<"Case Conversion succesfully sent to client"<<endl;
//CLOSE
close(newSocket);
close(serverFD);
return 0;
}