@mcgrailm の回答は、現在アドレスにバインドされているかどうかに関係なく、すべてのアクティブな(読み取り:無効になっていない) ネットワーク サービスを取得する方法を示しています。
対照的に、この回答は、現在の(プライマリ)IPv4 アドレスがバインドされているインターフェイスのネットワーク サービスを特定する方法を示しています。
残念ながら、情報はいくつかの情報源から引き出す必要があるため、これは簡単ではありません。
services
オブジェクト ( Dictionary から) には、System Events.sdef
現在バインドされているアドレスに関する情報が含まれていません。
- ただし、
service
オブジェクトのinterface
プロパティにはプロパティが含まれMAC address
ます。
- 現在の (プライマリ) IPv4 アドレスを返しますが
IPv4 address of (system info)
、悲しいことに、primary Ethernet address of (system info)
常に有線イーサネット インターフェイスの MAC アドレスを返します。これは、現在の IPv4 アドレスがバインドされているインターフェイスである場合とそうでない場合があります。
- したがって、現在の IPv4 アドレスに対応する MAC アドレスを特定するには、以下のソリューションを使用して、 の助けを借りて
do shell script
CLI からの出力を解析します。ifconfig
awk
# Obtain the [network] `service` instance underlying the
# current IPv4 address...
set serviceWithPrimaryIpv4Address to my networkServiceByIp4Address("")
# ... and extract the name.
set nameOfServiceWithPrimaryIpv4Address to name of serviceWithPrimaryIpv4Address
# ---- Helper handlers.
# SYNOPSIS
# networkServiceByIp4Address([addr])
# DESCRIPTION
# Given (one of) the local system's IPv4 address(es), returns the network service object whose interface
# the address is bound to (class `network service` is defined in `Sytem Events.sdef`).
# If `addr` is an empty string or a missing value, the current primary IPv4 address is used.
# An error is thrown if no matching service is found.
on networkServiceByIp4Address(addr)
local macAddress
set macAddress to my ip4ToMacAddress(addr)
tell application "System Events"
try
tell current location of network preferences
return first service whose (MAC address of interface of it) is macAddress
end tell
end try
end tell
error "No network service found matching IP address '" & addr & "'." number 500
end networkServiceByIp4Address
# SYNOPSIS
# ip4ToMacAddress([addr])
# DESCRIPTION
# Given (one of) the local system's IPv4 address(es), returns the corresponding network interface's
# MAC address (regardless of interface type).
# If `addr` is an empty string or a missing value, the current primary IPv4 address is used.
# An error is thrown if no matching MAC address is found.
on ip4ToMacAddress(addr)
if addr as string is "" then set addr to IPv4 address of (system info)
try
do shell script "ifconfig | awk -v ip4=" & ¬
quoted form of addr & ¬
" 'NF==2 && $2 ~ /^[a-f0-9]{2}(:[a-f0-9]{2}){5}$/ {macAddr=$2; next} $1 == \"inet\" && $2 == ip4 {print macAddr; exit}'"
if result ≠ "" then return result
end try
error "No MAC address found matching IP address '" & addr & "'." number 500
end ip4ToMacAddress
my ip4ToMacAddress("")