Python - Get MAC address of only the connected loc

2019-03-01 20:52发布

This question already has an answer here:

The goal is to collect the MAC address of the connected local NIC, not a list of all local NICs :)

By using socket and connect (to_a_website), I can just use getsockname() to get the IP, that is being used to connect to the Internet.

But from the IP how can I then get the MAC address of the local NIC ?

Main reason for the question is if there are multiple NICs.

6条回答
劫难
2楼-- · 2019-03-01 21:19

Use netifaces module. It's also on PyPI so you can install it via easy_install or pip.

查看更多
ら.Afraid
3楼-- · 2019-03-01 21:20

You cannot retrieve the MAC address of an external IP.

See the discussions over at how to get mac address of external IP in C# for more clarification.

查看更多
小情绪 Triste *
4楼-- · 2019-03-01 21:23

As vartec suggested netifaces should work well to go from IP->iface:

    import netifaces as nif
    def mac_for_ip(ip):
        'Returns a list of MACs for interfaces that have given IP, returns None if not found'
        for i in nif.interfaces():
            addrs = nif.ifaddresses(i)
            try:
                if_mac = addrs[nif.AF_LINK][0]['addr']
                if_ip = addrs[nif.AF_INET][0]['addr']
            except IndexError, KeyError: #ignore ifaces that dont have MAC or IP
                if_mac = if_ip = None
            if if_ip == ip:
                return if_mac
        return None

Testing:

    >>> mac_for_ip('169.254.90.191')
    '2c:41:38:0a:94:8b'
查看更多
三岁会撩人
5楼-- · 2019-03-01 21:27

Another roundabout way to get a systems mac id is to use the ping command to ping the system's name then performing an arp -a request against the ip address that was pinged. the downfall to doing it that way thou is you need to write the ping response into the memory of python and performing a readline operation to retrieve the ip address and then writing the corresponding arp data into memory while writing the system name, ip address, and mac id to the machine in question to either the display or to a test file.

Im trying to do something similar as a system verification check to improve the automation of a test procedure and the script is in python for the time being.

查看更多
唯我独甜
6楼-- · 2019-03-01 21:31

A primitive way of doing this would be to use the commandline tools available on your OS. Run the tool using the subprocess module (not os.system()!), collect the output, and parse it.

On Windows, the command you want is ipconfig /all.

On most Unices, including Linux, OSX and BSD, it's ifconfig.

There may be a better way of doing this without shelling out to a command-line utility, but I don't know it... yet.

Example output of ipconfig /all on Windows XP:

D:\Documents and Settings\LAYip>ipconfig /all

Windows IP Configuration

        Host Name . . . . . . . . . . . . : <redacted>
        Primary Dns Suffix  . . . . . . . : <redacted>
        Node Type . . . . . . . . . . . . : Hybrid
        IP Routing Enabled. . . . . . . . : No
        WINS Proxy Enabled. . . . . . . . : No
        DNS Suffix Search List. . . . . . : <redacted>
                                            <redacted>

Ethernet adapter Local Area Connection:

        Connection-specific DNS Suffix  . : <redacted>
        Description . . . . . . . . . . . : Intel(R) 82579LM Gigabit Network Con
nection #2
        Physical Address. . . . . . . . . : 5C-26-0A-60-8D-C7
        Dhcp Enabled. . . . . . . . . . . : Yes
        Autoconfiguration Enabled . . . . : Yes
        IP Address. . . . . . . . . . . . : xxx.xxx.28.29
        Subnet Mask . . . . . . . . . . . : 255.255.255.0
        Default Gateway . . . . . . . . . : xxx.xxx.28.254
        DHCP Server . . . . . . . . . . . : xxx.xxx.23.13
        DNS Servers . . . . . . . . . . . : xxx.xxx.23.13
                                            xxx.xxx.23.11
        Lease Obtained. . . . . . . . . . : Thursday, 12 April 2012 9:14:41 AM
        Lease Expires . . . . . . . . . . : Friday, 20 April 2012 9:14:41 AM

Ethernet adapter VirtualBox Host-Only Network:

        Connection-specific DNS Suffix  . :
        Description . . . . . . . . . . . : VirtualBox Host-Only Ethernet Adapter
        Physical Address. . . . . . . . . : 08-00-27-00-28-E6
        Dhcp Enabled. . . . . . . . . . . : No
        IP Address. . . . . . . . . . . . : 192.168.56.1
        Subnet Mask . . . . . . . . . . . : 255.255.255.0
        Default Gateway . . . . . . . . . :

Output of ifconfig under Linux:

lws@helios:~$ ifconfig
eth0      Link encap:Ethernet  HWaddr 00:25:22:db:8c:b6
          inet addr:10.1.1.2  Bcast:10.1.1.255  Mask:255.255.255.0
          inet6 addr: fe80::225:22ff:fedb:8cb6/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:322333 errors:0 dropped:0 overruns:0 frame:0
          TX packets:296952 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:40005876 (40.0 MB)  TX bytes:162343969 (162.3 MB)
          Interrupt:40 Base address:0x4000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:362 errors:0 dropped:0 overruns:0 frame:0
          TX packets:362 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:31806 (31.8 KB)  TX bytes:31806 (31.8 KB)
查看更多
神经病院院长
7楼-- · 2019-03-01 21:38

You Cannot catch the mac address from a socket.your need an ethernet frame, which can be found at the lowest layer of tcp processing chain.to do that you need to monitor(capture) your network traffic, find some packets by parsing the packet's header. and extract the required information such as mac address from it.

this is useful code span , that can help you to do that.

查看更多
登录 后发表回答