blob: b79d2b027459f79583ad7db09d74c3a3af653bbf [file] [log] [blame]
alshabib6ca05622017-01-31 14:08:36 -08001#
2# Copyright 2017 the original author or authors.
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"""
18Some network related convenience functions
19"""
20
21from netifaces import AF_INET
22
23import netifaces as ni
24
25
26def 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
38def 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
45if __name__ == '__main__':
Zack Williams7eb36d02019-03-19 07:16:12 -070046 print get_my_primary_local_ipv4()