How do I get the current path of a block? I need the current path, where my custom block is visible.
So, i have written this code 

class MyBlock extends BlockBase {

  public function build() {
    $currentPath= \Drupal::service('path.current')-&gt;getPath();  
    return array(
        '#markup' =&gt; $currentPath,
    );
  }
}


It is displaying the path where it was visible for first time; if I visit node/1, node/2, node/3 consecutively, it will print node/1 every time, because that was what I visited that first.
It might be happening due to block caching, but how do I get the path for the page showing the block?
Yes, this is because of block caching. The block is built once for the first request and then will stay in the cache forever, until you clear the cache.

You have to set a cache context on the url path:

'#cache' =&gt; ['contexts' =&gt; ['url.path']],


Then the block will get a cached version for every path.