Zsolt Haraszti | 86be6f1 | 2016-09-27 09:56:49 -0700 | [diff] [blame] | 1 | # |
Zsolt Haraszti | 3eb27a5 | 2017-01-03 21:56:48 -0800 | [diff] [blame] | 2 | # Copyright 2017 the original author or authors. |
Zsolt Haraszti | 86be6f1 | 2016-09-27 09:56:49 -0700 | [diff] [blame] | 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | # you may not use this file except in compliance with the License. |
| 6 | # You may obtain a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | # See the License for the specific language governing permissions and |
| 14 | # limitations under the License. |
| 15 | # |
| 16 | |
| 17 | """ |
| 18 | Some network related convenience functions |
| 19 | """ |
| 20 | |
| 21 | from netifaces import AF_INET |
| 22 | |
| 23 | import netifaces as ni |
| 24 | |
| 25 | |
| 26 | def get_my_primary_interface(): |
| 27 | gateways = ni.gateways() |
| 28 | assert 'default' in gateways, \ |
| 29 | ("No default gateway on host/container, " |
| 30 | "cannot determine primary interface") |
| 31 | default_gw_index = gateways['default'].keys()[0] |
| 32 | # gateways[default_gw_index] has the format (example): |
| 33 | # [('10.15.32.1', 'en0', True)] |
| 34 | interface_name = gateways[default_gw_index][0][1] |
| 35 | return interface_name |
| 36 | |
| 37 | |
| 38 | def get_my_primary_local_ipv4(ifname=None): |
| 39 | ifname = get_my_primary_interface() if ifname is None else ifname |
| 40 | addresses = ni.ifaddresses(ifname) |
| 41 | ipv4 = addresses[AF_INET][0]['addr'] |
| 42 | return ipv4 |
| 43 | |
| 44 | |
| 45 | if __name__ == '__main__': |
| 46 | print get_my_primary_local_ipv4() |