# ipaddr filter: Calculating default gateway

**URL:** <https://forum.ansible.com/t/ipaddr-filter-calculating-default-gateway/21504>\
**Category:** Ansible Developer\
**Created:** [May 20, 2016, 11:13am UTC](https://forum.ansible.com/t/ipaddr-filter-calculating-default-gateway/21504 "2016-05-20T11:13:40Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Daniel\_Schroeder](https://avatars.discourse-cdn.com/v4/letter/d/54ee81/32.png) [@Daniel\_Schroeder](https://forum.ansible.com/u/Daniel_Schroeder)\
**Post date:** [May 20, 2016, 11:13am UTC](https://forum.ansible.com/t/ipaddr-filter-calculating-default-gateway/21504/1 "2016-05-20T11:13:40Z")

</div>

I wanted to calculate the default gateway from a CIDR. The _ipaddr_ filter has an undocumented gateway/router option but it results in unexpected values.

Here is the responsible [method](https://github.com/ansible/ansible/blob/7af47a3886d5a2ebdc49f79564d84a336e10ffcb/lib/ansible/plugins/filter/ipaddr.py#L86):

`def _gateway_query(v): if v.size > 1: if v.ip != v.network: return str(v.ip) + '/' + str(v.prefixlen)`

How is this a gateway? It basically returns the given CIDR.

Since this is not documented it’s hard to guess what was the intention behind this.

I’d like to send a pull request to change this but first wanted ask what you think about it. My proposal would be to change the method to:

`def _gateway_query(v): if v.size > 1: return str(netaddr.IPNetwork(str(v.ip) + '/' + str(v.prefixlen))[1])`

I know the gateway could be anything and does not necessarily have to be the first IP of the network range. But still this more or less the default. What do you think?

Greetings,

Daniel

---

<div class="post-metadata">

**Author:** ![Michel\_Blanc1](https://avatars.discourse-cdn.com/v4/letter/m/fbc32d/32.png) [@Michel\_Blanc1](https://forum.ansible.com/u/Michel_Blanc1)\
**Post date:** [May 20, 2016, 12:05pm UTC](https://forum.ansible.com/t/ipaddr-filter-calculating-default-gateway/21504/2 "2016-05-20T12:05:04Z")

</div>

Hi Daniel,

I am not sure replacing something wrong by something equally wrong is  
the proper way to do it.

If you can not use ansible\_default\_ipv4.gateway because you are working  
on something that is not covered by gather\_facts, then you really should  
provide the gateway explicitly.

M
