blob: a082eeba62d887eb14a7d6f2248499a331c46bcb [file] [log] [blame]
Zsolt Haraszti86be6f12016-09-27 09:56:49 -07001#
Zsolt Haraszti3eb27a52017-01-03 21:56:48 -08002# Copyright 2017 the original author or authors.
Zsolt Haraszti86be6f12016-09-27 09:56:49 -07003#
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
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070025def get_my_primary_interface():
26 gateways = ni.gateways()
27 assert 'default' in gateways, \
28 ("No default gateway on host/container, "
29 "cannot determine primary interface")
30 default_gw_index = gateways['default'].keys()[0]
31 # gateways[default_gw_index] has the format (example):
32 # [('10.15.32.1', 'en0', True)]
33 interface_name = gateways[default_gw_index][0][1]
34 return interface_name
35
36
37def get_my_primary_local_ipv4(ifname=None):
khenaidooccc42252017-07-06 23:00:49 -040038 try:
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 except Exception as e:
44 return None
Zsolt Haraszti86be6f12016-09-27 09:56:49 -070045
46
47if __name__ == '__main__':
48 print get_my_primary_local_ipv4()