:::: MENU ::::

Learning is a constant process of discovering yourself.

Saturday, April 20, 2024

It stands for Secure Socket Layer/Transport layer Security. It is encryption based internet security protocol which works on transport layer of OSI model. It was first developed by Netscape in 1995. After that some modification was made by IETF (Internet Engineering Task Force) and renamed as TLS. So SSL is direct predecessor of TLS, and both are logically same except some insignificant modification.

It prevents man in the middle (MITM) attack. The intruders can intercept data and can damage data integrity without awareness of senders and recipents. A web server with SSL protocol behave like HTTPS.

How does SSL/TLS work?

SSL/TLS protocol need activation between client-server. Symmetric key encryption is going for data integrity. But asymmetric key encryption technique is required for exchanging symmetric key between client-server. Without asymmetric key technique, symmetric key can be vulnerable.



SSL handshake has multiple steps. Without handshaking TCP/UDP connection won’t be established. The picture below is trying to explain the abstract required steps.


Credits:

https://www.youtube.com/watch?v=0yw-z6f7Mb4&t=1051s

https://www.cloudflare.com/learning/ssl/what-is-ssl/

Saturday, November 25, 2023

Java can achieve callback paradigm using functional interface. It's widely used in APIs. Java developer are fortunate to have these. Lets jump into it.

First of all we have to know about what is callback function. According to wikipedia:


In computer programming, a callback or callback function is any reference to executable code that is passed as an argument to another piece of code; that code is expected to call back (execute) the callback function as part of its job. This execution may be immediate as in a synchronous callback, or it might happen at a later point in time as in an asynchronous callback. They are also called blocking and non-blocking.

So in plain language, call back is passed in another function's arguments. That call back is called when it's required to call from. Java hasn't familiar with callback functions in the same way as JavaScript,primarily due to differences in their programming paradigms.

However, Java manages itself to achieve similar functionality. Using functional interface it's possible to achieve in java. Do you know it comes from java 8!!!

Let's back to the coding example:

What is functional interface? "A functional interface is an interface that contains only one abstract method.", according to geeksforgeeks. Example DataProcessor class which is used to demostrate callback function.
Code snippet:


  //define a functional interface for the callback
  public interface Callback {
  void callback(String result);
}

// Class that uses the callback
class DataProcessor {
    void processData(String data, Callback callback) {
        // Simulate processing data
        String result = "Processed: " + data.toUpperCase();

        // Invoke the callback
        callback.onCallback(result);
    }
}

public class CallbackExample {
    public static void main(String[] args) {
        DataProcessor dataProcessor = new DataProcessor();

        // Use an anonymous class as a callback
        dataProcessor.processData("Hello, World!", new Callback() {
            @Override
            public void onCallback(String result) {
                System.out.println("Callback result: " + result);
            }
        });

        // Using lambda expression for the callback
        dataProcessor.processData("Java Callback", result -> {
            System.out.println("Lambda Callback result: " + result);
        });
    }
}
In this example:

- The Callback interface defines a single method onCallback.

- The DataProcessor class takes an instance of the Callback interface as a parameter to its processData method.

- In the main method, an anonymous class and a lambda expression are used to provide different implementations of the callback.

While Java doesn't have the exact syntax for callback functions as in JavaScript, the use of interfaces, anonymous classes, and lambda expressions provides a flexible way to achieve similar behavior. This approach is commonly used in Java APIs and libraries.


Do you know java functional programming, Supplier, and Consumer interfaces??

Sunday, November 5, 2023

Agenda

  • What is Redis? Use cases and benefits of Redis?
  • Why Redis is suitable for microservices apps?
  • How Redis supports multiple data formats?
  • Data persistence and Recovery with redis?
  • How to optimize memory cost with Redis on Flash?
  • Scaling Redis & High Availability across multiple geographic locations?

What is Redis? Use cases and benefits of Redis?

It stands for Remote Dictionary Server. It stores data on computer’s memory (RAM). It is often used for caching data on top of other database (e.g. MySQL). But Redis is a fully fledged primary db. That can be used for persistence multiple data formats.

How Redis supports multiple data formats?

It allows developer to store different data structures e.g. graph, document, relational data etc.



Characteristics:
  • In memory data structure store
  • used as a NoSQL database
  • distributed cache
  • message broker

Supports various data structure

  • string
  • hashes
  • list
  • sets
  • sorted sets
  • bitmaps
  • hyperloglog
  • geo spatial indexes

Architecture

  • Redis client
  • Redis Server

Redis client sends and receives data from redis Server. It’s also possible master-slave configuration for distributed system.

Advantages

  • Exceptionally fast
  • persistence
  • rich support of data types
  • atomicity
  • multi-utility tool, caching, message queue etc.

Redis installation

on Linux: https://redis.io/docs/getting-started/installation/install-redis-on-linux/

To check if Redis is running on your local Linux machine after installing it via Snap, you can use the following steps:

  1. Status Command: You can check the status of the Redis service by running the following command in your terminal:
    sudo systemctl status snap.redis.server

    This command will show the status and information about the Redis service.

  1. Redis-CLI: You can also check if Redis is running by using the Redis command-line interface (redis-cli). Open a terminal and run the following command:
    redis-cli

    If Redis is running, this command will start the Redis CLI, and you'll see a prompt like 127.0.0.1:6379>. This indicates that Redis is up and running.

Redis Data types

String

  • 127.0.0.1:6379> keys *

    display all keys

  • > set [key] [value]

    it will set value on key. Redis sets key-value pair.

  • > get [key]

    It will display value of given [key]

  • > mset [key] [value] [key] [value]
  • > mget [key] [key]
  • > strlen [key]
  • > incr [key]

    it will increment value of given key.

  • > incrby [key] [value]
  • > decr [key]
  • > decrby [key] [value]
  • > incrbyfloat [key] [value]
  • > expire [key] [duration]

    expiring a key-value after a duration

  • > setex [key] [duration] [value]

list

  • > flushall

    it clears all key-value pairs

  • > lpush [list-name] [list-item]

    insert

  • > lrange [list-name] [start-index] [end-index]

    e.g. > lrange country 0 -1

  • > rpush [list-name] [list-item]
  • > llen [list-name]
  • > lpop [list-name]

    it removes last left-sided item

  • > rpop [list-name]

    it removes last right-sided item

  • > lset [list-name] [index] [item]

    it assigns [item] to [index] of [list-name]

  • > linsert [list-name] before|after [pivot-value] [item-value]
  • > lindex [list-name] [index]

    get value of index.Index is 0 based

  • > lpushx [list-name] [item]

    it will return 0 if [list-name] is not exist before.

  • > rpushx [list-name] [item]

set

  • > sadd [set-name] [set-item]
  • > sadd [set-name] [set-items]
  • > smembers [set-name]
  • > scard [set-name]

    return the length of set. card means cardinality

  • > sismember [set-name] [value]

    check is given [value] member of [set-name]

  • > smembers [set-name]
  • > sdiff [set1] [set2]
  • > sdiffstore [newset] [set1] [set2]
  • > sinter [set1] [set2] [set3]
  • > sinterstore [newset] [set1] [set2]
  • > sunion [set1] [set2] [set3]
  • > sunionstore [newset] [set1] [set2]

sorted set

  • > zadd [set-name] [score] [value]
  • > zadd [set-name] [score] [value] [score] [value]
  • > zrange [set-name] [start] [end]

    display all sorted elements

  • > zrange [set-name] [start] [end] withscores
  • > zcard [set]
  • > zcount users [min] [max]
  • > zrem [set] [value]

    it removes the set value

  • > zrevrange [set] [start] [end] withscores
  • > zscore [set] [value]
  • > zincrby [set] [scrore] [value]

hyperloglog

  • > pfadd [hll] [value]
  • > pfcount [hll]

Hash

keys are case-sensitive

  • > hset [hash-name] [key] [value]

  • > hkeys [hash]
  • > hvals [hash]
  • > hgetall [hash]
  • > hexists [hash] [key]

    return 0 if key isn’t exist in [hash], otherwise return 1

  • > hlen [hash]

    return the count of keys.

  • > hmset [hash] [key1] [value1] [key2] [value2]
  • > hmget [hash] [key1] [key2]
  • > hincrby [hash] [key] [incrementbyValue]

    e.g. hincrby myhash age 5

  • > hincrbyfloat [hash] [key] [incrementbyValue]
  • > hdel [hash] [key]
  • > hstrlen [hash] [key]

    return the length of value that is stored in [key] into [hash]

  • > hsetnx [hash] [key] [value]

    it saves key-value pair, if key isn’t exist before.

Redis transaction

  • > multi

    It helps to execute multiple commands in one transaction

    > multi
    OK
    > set name saiful
    Queued
    > get name
    Queued
    > set b 1
    Queued
    > exec
    OK
    (nil)
    OK
    OK
  • > discard

    it discard the transaction

    > multi
    OK
    > set name saiful
    Queued
    > get name
    Queued
    > set b 1
    Queued
    > discard
    OK
  • > watch

Redis pub-sub

  • > subscribe [channel-name]
    > subscribe news
    Reading messages ... (press Ctrl-C to quit)
    1) subscribe
    2) news
    3) (integer) 1
  • > subscribe [channel1] [channel2]
  • > psubscribe [channel-name-regex] [channel-name-regex]
    psubscribe news* h?llo o[ai]ll
  • > publish news [message]
    > publish news "new breaking news"
    (integer) 2

    the output 2 means there are two subscriber for news channel

  • > pubsub channels
  • > pubsub numsub [channel-name]
  • > pubsub numpat

Redis scripts

In Redis, a script refers to a Lua script that you can execute on the server. These scripts are used for complex operations that may involve multiple Redis commands. Redis supports Lua scripting as a way to perform atomic operations, batch operations, and more.

Here are some key points about Redis scripts:

  1. Lua Scripting: Redis uses the Lua scripting language for its scripting capabilities. Lua is a lightweight, embeddable scripting language known for its simplicity and efficiency.
  1. Atomic Execution: When you run a Lua script in Redis, it is executed atomically on the server. This means that the script's commands are executed as a single, indivisible operation. This is useful for ensuring that multiple commands are executed in a transaction-like manner.
  1. Batch Operations: Scripts are particularly useful when you need to perform multiple Redis operations in a single network round trip. Instead of sending multiple Redis commands over the network, you can send a single script that performs all the required operations.
  1. Evaluating Scripts: You can evaluate a Lua script using the EVAL or EVALSHA commands in Redis. EVAL allows you to provide the Lua script as a parameter, while EVALSHA takes a SHA1 hash of the script, which can be useful for caching commonly used scripts.
  1. Arguments: Redis scripts can accept arguments, which are passed to the script as part of the evaluation. This makes scripts dynamic and allows you to reuse them with different data.
  1. Return Values: Lua scripts can return values, and these return values can be used in your application. This allows you to perform computations and data manipulation on the server side.
  1. Error Handling: Redis scripts have error-handling capabilities. You can use the redis.error_reply and redis.status_reply functions in Lua to return specific errors or status messages to the client.
  1. Script Caching: Redis caches scripts internally based on their SHA1 hashes. This reduces the overhead of sending the same script multiple times.

Lua scripting in Redis is a powerful feature that can help you optimize and simplify complex operations while maintaining data integrity. It's commonly used for scenarios like implementing custom data processing logic, complex transactional operations, and more.

Example of commands

  • > eval “redis.call(’set’, KEYS[1],ARGV[1])” [numberofpair] [key] [value]

    e.g. eval “redis.call(’set’, KEYS[1], ARGV[1])” 1 name saiful

Connections and Security

  • > ping
  • > echo hello
  • > client list
  • > client setname [client-name]
  • > client kill id [client-id]
  • > config set requirepass [pass]
  • > auth [pass]

Redis benchmark

  • > redis-benchmark -n 1000 -d 1000000 -c 200

Measuring latency

If you are experiencing latency problems, you probably know how to measure it in the context of your application, or maybe your latency problem is very evident even macroscopically. However redis-cli can be used to measure the latency of a Redis server in milliseconds, just try:

redis-cli --latency -h `host` -p `port`

intrinsic latency comes for operating system, e.g. the environment where redis server is running. keep in mind that the intrinsic latency may change over time depending on the load of the system.

redis-cli --intrinsic-latency 100

Credits:

https://redis.io/docs/management/optimization/latency/#:~:text=Redis uses a mostly single,the requests are served sequentially.

https://redis.io/docs/management/optimization/latency/#measuring-latency

https://redis.com/blog/you-dont-need-transaction-rollbacks-in-redis/

Friday, February 10, 2023

We are going to learn Linux Operating system. It will helps you to become Power user of Linux Operating system in your workplace. Let's get started.

First lesson is divided into two parts:
Basic Operating system navigation.
1. navigating from one directory to another
2. getting file information
3. removing files and directories.
File and text manipulation
1. searching through your directories
2. find a specific file
3. copying and pasting
4. chaining commands
Linux terminal has an interpreter who interpretes linux commands. This interprete is called Shell. and the language of shell is named Bash.



bin, etc, dev, home, proc, usr, var these are directories located at Root directory. All have specific meaning.

bin: keeps essential binnaries and program like system application or program.
etc: store system configuration files.
dev: whenever a device, it might be virtual device, is connected to system. A device file is created in /dev location. Device type could be character or block type and many more. character type device could be recognized by 'c' and 'b' for block device. Important notes on disk device are 1. sometimes you might see sda,sdb etc. All of these are disk devices. Here, sda has special meaning. sda device is detected by computer first.



history
Copy command: cp from to 
-r flag used for recursive action

*: wildcard is used for pattern

mv: mv from to 
used for move or rename file or folder


remove comamnd, it remove file permanently unlike windows
rm [file name]

 display file content: cat, less, head, tail [filename]


modify file content
nano or other file editor


linux searching within files:
grep [searched_word] filename


Input, output and stderr 2>
sudo = super user do

--------$ sudo su - 
this command substitue current user to another. If you doesn't specify any user, then by default root user willl be here.

--------$ cat /etc/group 
See group information

--------$ cat /etc/passwd 
See user information 
 

 passwd [username]
 sudo passwd -e [username]
 sudo useradd [new username]
 sudo userdel [new username]
 
 
 
 Permission
 u - file owner
 g - stands for group
 o - for other
 
 chmod u+x [filename]
 chmod u-x [filename]
 
 chmod ugo+x [filename]
 
 chmod 754 [filename/dirname]
 
 sudo chown [username] [filename]
 sudo chgrp [groupname] [filename]
 
 
 Special permission 
 setuid, setgroupid, sticky bit
 symbolic sign is s, s, and t. where numeric sign are 4,2,1
 setuid: is a special permission level. where user can use file without direct permission of owner.
 setgroupid: can use file belonging to group.
 sticky bit: anyone can add and write file, except deletion.
 
 
 software distribution:
 ubuntu
 
 .deb or debian package
 
 install and removing standalone debian package
 
 sudo dpkg -i [filename]
 sudo dpkg -r [applicationname]
 
 
 7z e [archive filename]
 
 
 
 # package manager
 1. apt, advanced package tool, is a package manager of ubuntu linux distribution. 
 
 -----------$ sudo apt install [soft name]
 -----------$ sudo apt remove [softname]
2. snap
Reference: https://www.baeldung.com/linux/snaps-intro


 # what command can you use to see the version of the kernel on your Linux system?
---------- $ uname -r
 You can upgrade linux version. You need to use these commands:
 --------- $ sudo apt update
 --------- $ sudo apt full-upgrade

 then after rebooting you are able to use new kernel.






 # File systems:
 Major file systems are NTFS, ext4, FAT32. 

 Remarkable notes:
    FAT32, is an excellent file system that compatible with windows, linux and MacOS.
    NTFS, file system that is compatible to both windows and linux. NTFS is recommanded file system for windows.
    ext4, is only work with linux distro. recommanded for linux.

    FAT32 has some shortcomings though.
    It doesn't support files larger than 4 gigabytes 
    It doesn't support file system larger than 32 gigabytes. It's great choose for small USB device.


Network file system is compatible for all OS and overcome shortcomings of FAT32.


Disk anatomy:
    Some terminalogy are associated with Disk. They are partition, volume, partition table.
    
    Parition: The piece of a disk that you can manage. To add a file system to a disk first you need to create a partition. It's possible to have different file system on different partition, but same disk. 

    Volume: Without file system on partition is called volume. When you format a file system on a partition, it becomes a volume.

    Partition table: is a scheme that tell how the disk is partitioned. This scheme helps to make partition on same disk. Major two partition table scheme: Master Boot Record (MBR); GUID Partition Table (GPT).
    MBR and GPT have mentionable districtions. MBR is traditional partition scheme and old standard and mostly used for windows OS. It has limitation to size of max 2TB. It uses primary partition. There can have 4 primary partition.

    GPT is new standard which overcomes limitions of size and number of partition. It can use 2TB or greater volume size and one type of partition and unlimited partitions. new BIOS standard UEFI is compatible with GPT partition.

# Disk partition:
    ------------$ sudo parted -l
    It will show all disk with their partition table and number of partition in details.

    -----------$ sudo parted [disk name, e.g. /dev/sda]
    it prompts another terminal, give control on disk. We can run specific command for disk.
    ------------- (parted) print
    it shows details info of it.
    --------------- (parted) mklabel [gpt|mbr]
    it sets partition table value.

    --------------- (parted) mkpart primary ext4 1MiB 5GiB
    it makes partition into disk with these given info.
    
    ------------$ mkfs -t ext4 /dev/sdb[partition number]
    it makes file system on it, and make ready for use. But remember, without mounting OS can't use it.

# Mount and Unmount
    -----------------$ sudo mount [storage] [specific_dir] e.g. sudo mount /dev/sdb1 /my_usb/
    it mounts secondary storage devices to specific directory. In this example, storage /dev/sdb1 and specific directory is /my_usb/

    Sometimes, we don't mount explicitly, OS do for users.

    --------------$ sudo umount /my_usb
    it unmounts the storage.
    

    -----------------$ cat /etc/fstab
    fstab stands for file system table, stores mounting info 

# swap memory
    In linux, swap memory is a dedicated space of memory.
    Steps which are followed to make a swap memory:
        1. make a partition with "linux-swap" file system via parted tool.
        2. sudo mkswap [partition_name, e.g. /dev/sdb2]
        3. sudo swapon [partition_name, e.g. /dev/sdb2]
        4. if we want this swap space active automatically with boot up, then need an entry in /etc/fstab configuration file.

# disk usage   
    --------------$ df -h 
    find how much free of Disk. here -h flag is for human readable format. 

Thursday, October 27, 2022

Any programming language has data types that can store data in memory e.g. primitive: integer, floating, string, reference variable: object variable, and more. Sometimes we want to convert one data type into another. So in a simple sentence, type casting is the way of assigning one data type value to another data type.
In java language, it's very important to understand primitive type casting and reference or object variable type casting. Though most programmers know about typecasting in brief and use casting more often in their coding, they face some expected hassle in casting. e.g converting parent object to child object, String to int, or vice-versa, etc. So Clear knowledge about casting could help anyone to avoid unexpected bugs.


So let's Know In Forms this article's content; Moreover first Know and then Informs others about this content.
We believe knowledge sharing is the power of the next generation.





Friday, August 26, 2022


Arrays: 

Java Arrays is an object that stores similar types of objects. It stores data in a contiguous memory location.  It's a primitive data structure of java. 

List:

The list is an interface that extends the collections interface. It's implemented by ArrayList, LinkedList, Stack, Queue, Vector, etc.


Set:
A collection that doesn't allow duplicate elements inside it. More formally, the set contains no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. This interface is implemented by HashSet, TreeSet, EnumSet, etc.
So formal characteristics:
1. it contains the distinct element
2. doesn't guarantee the order of elements.


Map:  

A map is an interface, it's a collection of key-value pairs. Note that the key can't be duplicated and each key can map to at most one value.
One very important point: if you use any object as a key, then must override equals and hashCode methods, otherwise it will produce the wrong result. It is implemented by HashMap, TreeMap, etc.




Map interface implementation

Java HashMap implementation:

HashMap implements an array of nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Keys and Values. There are four fields in HashMap.



        1. generate hashCode for a given key
        2. calculate array index value using formula:    index = hashCode & (size-1).
                Note that the default size of the array is 16.
        3. put in that index as a LinkedList node.

insertion and accessing amortized complexity is O(1). you can check out link.

Difference Among HashMap, TreeMap, LinkedHashMap.
HashMap
  • HashMap has the complexity of O(1) for insertion and lookup.

  • HashMap allows one null key and multiple null values.

  • HashMap does not maintain any order.

TreeMap
  • TreeMap has the complexity of O(logN) for insertion and lookup.

  • TreeMap does not allow a null key but allows multiple null values.

  • TreeMap maintains order. It stores keys in sorted and ascending order. It is implemented by a Red-Black tree which is a balanced Binary Search tree (BST). But It is not thread-safe.

LinkedHashMap
  • LinkedHashMap has the complexity of O(1) for insertion and lookup.

  • LinkedHashMap allows one null key and multiple null values.

  • LinkedHashMap maintains the order in which key-value pairs are inserted.



Last modified: 08.10.2022

Friday, June 17, 2022

OSPF stands for Open Shortest Path First. OSPFv2 is used along with IPv4 network layer protocol. But OSPFv3 is for IPv6.
It is developed as an alternative distance vector algorithm (routing information protocol. abbreviation- RIP).
Lets make clear concept about link state: Every router has multiple interfaces and each interface acts of a network segment and each of them is called a link of network. Network segment could be stub network, connected two routers etc. So Link-State refers the information of the state of link. A link-state info could have the network prefix, prefix length, and cost etc.
OSPF protocol can be summarize into three components. 
They are 
1. Routing protocol messages: They are five types. 
2. Constructing data structures: they are three types; Each of them has special significance. They are 
a. adjacency database:
It keeps information about its neighbors e.g. a router has 3 interfaces connected with other routers, so it has 3 neighors. this database will be unique for each router.
b. Link-state database: 
Most important table it is. This database has complete struture of topology. E.g. suppose a router belongs to an area 0 in which somehow total 5 routers are connected with each others and they could be in star topology, mesh topology etc. So all router belong to same topology must have identical LSDB.
c. Forwarding database: 
It keeps routes generated by running routing algorithms (Shortest path first)
3. Applied algorithm: Dijkstra Shortest path first.
routing protocol messages:
Routers running OSPF exchange messages to convey routing information using five types of packets. These packets, as shown in the figure, are as follows:

1. Hello packet
Discovering neighbour routers.
2. Database description packet (DBD). 
Note that it means exchaning LSDB/ topology table to other routers. It is necessary, to make sure the LSDB is identical on every router in the area.
3. Link-state request packet (LSR)
Note that, it is used by a router when a router needs specific info about an entry of link state table.
4. Link-state update packet (LSU)
it is actually a response of request of LSR.
5. Link-state acknowledgment packet
it is an acknowledgment of receivng response packet (LSU).

Most generic processes that a router go through to build its routing table are:
1. collect neighbouring info and build neighbour table using Hello protocol packet.
2. exchange neighbour table-info other router; its called exchaning link state advertisements (LSAs) and LSUs contains LSAs.
3. establishing link state database
4. execute SPF (Shortest Path First) algorithm
5. build routing table


OSPF configuration
1. enable OSPFv2 on router
command: (config)# router ospf <process id>
Note for process id:
The process-id value represents a number between 1 and 65,535 and is selected by the network administrator. The process-id value is locally significant, which means that it does not have to be the same value on the other OSPF routers to establish adjacencies with those neighbors. It is considered best practice to use the same process-id on all OSPF routers.
Some important terms:
Router id:
It is represented as IPv4 address. The router ID is used to uniquely identify an OSPF router. All OSPF packets exchanged among other routers have the router ID of the originating router. Every router requires a router ID to participate in an OSPF domain. The router ID can be defined by an administrator or automatically assigned by the router.
So, adminstrator could have good control on network, if the router id is configured in the recommanded ways.
there are three available ways:
1. explicitly configure the router id through command. It is highly recommanded way.
(config-router)# router-id <rid>
2. Secondly if it's not configured in explicit way, router tries to choose configured highest IPv4 loopback address.
(config)#interface loopback 1
(config-if)# ip address 1.1.1.1 255.255.255.255
(config-if)# end
justifying:
R1# show ip protocols | include Router ID
Expected output: Router ID 1.1.1.1

3. Lastly, router uses highest IPv4 address from active IPv4 interface's addresses.


OSPF configuration on networks:
There are two types of networks: point-to-point and multiaccess network.
OSPF can be enabled on router using Network command.
(config-router)# network <network-address> <wildcard-address> area <area-id>
alternative process is:
(config-router)# network <direct interface address> <quad zero> area <area-id>
The advantages of this command is no need to calculate wildcard address from subnet mask.
Another alternative process is:
(config-if)# ip ospf <process-id> area <area-id>
(when an interface or a router is activated as OSPF router. All OSPF interface sends out hello packet and by default they are supposed to be in multiaccess network.
so to make an interface as point-to-point network the following command is applied on that interface:
(config-if)# ip ospf network point-to-point
Note:
1. The network-address wildcard-mask syntax is used to enable OSPF on interfaces. Any interfaces on a router that match the network address in the network command are enabled to send and receive OSPF packets.
    2.The area area-id syntax refers to the OSPF area. When configuring single-area OSPFv2, the network command must be configured with the same area-id value on all routers. Although any area ID can be used, it is good practice to use an area ID of 0 with single-area OSPFv2. This convention makes it easier if the network is later altered to support multiarea OSPFv2.
OSPF in Multi-Access Network:
One important difference apart from point-to-point network is DR controls the distribution of LSAs. DR uses multicast address 224.0.0.5 for distribution and 224.0.0.6 multicast address is used for listening from DROTHER routers. Because DROTHERs use the multiaccess address 224.0.0.6 (all designated routers) to send OSPF packets to the DR and BDR.
In brief the role of DR is:
Only the DR and the BDR process the LSA sent by DROTHER router using the multicast IPv4 address 224.0.0.6. The DR then sends out the LSA to all OSPF routers using the multicast IPv4 address 224.0.0.5.
(Ethernet LANs are the most common example of broadcast multiaccess networks.)
verifying interface ospf state:
# show ip ospf interface <interface name>
It shows neighbor list of router:
#show ip ospf neighbor 
OSPF DR and BDR elections are not pre-emptive. If a new router with a higher priority or higher router ID is added to the network after the DR and BDR election, the newly added router does not take over the DR or the BDR role. This is because those roles have already been assigned. The addition of a new router does not initiate a new election process.
Router(config-router)# auto-cost reference-bandwidth Mbps
ip ospf cost 
Verification:
# show ip ospf
Verify the OSPF process
# show ip ospf neighbor
to display neighbor adjacencies.
# show ip protocols
# show ip ospf interface brief
# show ip ospf interface <interface name>
# show ip route ospf

Wednesday, June 1, 2022

NAT: Network Address Translation and PAT: Port Address Translation

Terms:
NAT Pool: A container of Public IPv4 addresses maintained NAT-enabled router. NAT enabled router can pull one of the public IPv4 addresses from NAT Pool while translating from private IPv4
addresses to public addresses.
Note: A NAT router typically operates at the border of a stub network; A stub network comprises one or more network with a single connection from neighboring network. 

NAT Terminalogy:
- Inside local
- Inside global
- Outside local
- Outside global
Local address - A local address is any address that appears on the inside portion of the network.
Global address - A global address is any address that appears on the outside portion of the network.
Inside address - The address of the device which is being translated by NAT.
Outside address - The address of the destination device.


Lets make it clear with an example:
Suppose a personal computer PC1 (ip:192.168.0.1) is connected to a private network with a NAT-enabled router. NAT pool has one public IPv4 address (201.165.12.1). Now PC1 is trying to send a data packet to a web server (105.15.12.5). 

NAT table will be generated as follow:
Inside local address: 192.168.0.1
Outside local address: 105.15.12.5

Inside global address: 201.165.12.1
Outside global address: 105.15.12.5
NAT technology can be divided into two important types:
1. Static NAT
2. Dynamic NAT
Useful Commands for static NAT configuration:
make translation entry:
    (config) # ip nat inside source static <private-address> <public-address>
configuring inside and outside interface:
    (config-if)# ip nat [inside | outside]
Verification:
# show ip nat translation
# show ip nat statistics
Useful Commands for Dynamic NAT Configurations:
Step 1: make NAT Pool:
(config)# ip nat pool <pool-name> <starting-address> <end-address> <net-mask>
Step 2: make a ACL list
(config)# access-list <access-list-number> <ip-address> <wildcard-mask>
Step 3: bind ACL list to NAT pool
(config)# ip nat inside source list <ACL name/number> pool <NAT-pool-name>
Step 4: configuring inside interface similiar to static NAT
(config-if)# ip nat inside
Step 5: configuring outside interface similiar to statice NAT
(confi-if)# ip nat outside
Verification commands are the same as Static NAT.
Note: # show running-config | include NAT
can be useful to verify actual commands.
    PAT configuration:
1. Single inside global address
R2(config)# ip nat inside source list 1 interface serial 0/1/1 overload
R2(config)# access-list 1 permit 192.168.0.0 0.0.255.255
R2(config)# interface serial0/1/0
R2(config-if)# ip nat inside
R2(config-if)# exit
R2(config)# interface Serial0/1/1
R2(config-if)# ip nat outside

2. Pool of inside global address
R2(config)# ip nat pool NAT-POOL2 209.165.200.226 209.165.200.240 netmask 255.255.255.224
R2(config)# access-list 1 permit 192.168.0.0 0.0.255.255
R2(config)# ip nat inside source list 1 pool NAT-POOL2 overload
R2(config)# 
R2(config)# interface serial0/1/0
R2(config-if)# ip nat inside
R2(config-if)# exit
R2(config)# interface serial0/1/1
R2(config-if)# ip nat outside
R2(config-if)# end