Skip to content

Commit

Permalink
fix: android.adb get_ip_address() api method for android version>=6.0
Browse files Browse the repository at this point in the history
(cherry picked from commit 5dc3306)
  • Loading branch information
rockywhisper authored and yimelia committed Sep 24, 2020
1 parent c1d8372 commit e4d7625
Showing 1 changed file with 34 additions and 18 deletions.
52 changes: 34 additions & 18 deletions airtest/core/android/adb.py
Original file line number Diff line number Diff line change
Expand Up @@ -1264,7 +1264,7 @@ def clear_app(self, package):

def get_ip_address(self):
"""
Perform several set of commands to obtain the IP address
Perform several set of commands to obtain the IP address.
* `adb shell netcfg | grep wlan0`
* `adb shell ifconfig`
Expand All @@ -1276,41 +1276,57 @@ def get_ip_address(self):
"""

def get_ip_address_from_interface(interface):
"""Get device ip from target network interface."""
# android >= 6.0: ip -f inet addr show {interface}
try:
res = self.shell('ip -f inet addr show {}'.format(interface))
except AdbShellError:
res = ''
matcher = re.search(r"inet (\d+\.){3}\d+", res)
if matcher:
return matcher.group().split(" ")[-1]

# android >= 6.0 backup method: ifconfig
try:
res = self.shell('ifconfig')
except AdbShellError:
res = ''
matcher = re.search(interface + r'.*?inet addr:((\d+\.){3}\d+)', res, re.DOTALL)
if matcher:
return matcher.group(1)

# android <= 6.0: netcfg
try:
res = self.shell('netcfg')
except AdbShellError:
res = ''
matcher = re.search(interface + r'.* ((\d+\.){3}\d+)/\d+', res)
if matcher:
return matcher.group(1)
else:
try:
res = self.shell('ifconfig')
except AdbShellError:
res = ''
matcher = re.search(interface + r'.*?inet addr:((\d+\.){3}\d+)', res, re.DOTALL)
if matcher:
return matcher.group(1)
else:
try:
res = self.shell('getprop dhcp.{}.ipaddress'.format(interface))
except AdbShellError:
res = ''
matcher = IP_PATTERN.search(res)
if matcher:
return matcher.group(0)

# android <= 6.0 backup method: getprop dhcp.{}.ipaddress
try:
res = self.shell('getprop dhcp.{}.ipaddress'.format(interface))
except AdbShellError:
res = ''
matcher = IP_PATTERN.search(res)
if matcher:
return matcher.group(0)

# sorry, no more methods...
return None

interfaces = ('eth0', 'eth1', 'wlan0')
for i in interfaces:
ip = get_ip_address_from_interface(i)
if ip and not ip.startswith('172.') and not ip.startswith('127.') and not ip.startswith('169.'):
return ip

return None

def get_gateway_address(self):
"""
Perform several set of commands to obtain the gateway address
Perform several set of commands to obtain the gateway address.
* `adb getprop dhcp.wlan0.gateway`
* `adb shell netcfg | grep wlan0`
Expand Down

0 comments on commit e4d7625

Please sign in to comment.