How to get the local mac address?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Daniel Crespo

    How to get the local mac address?

    Hi, I tried:

    import ctypes
    import socket
    import struct

    def get_macaddress( host):
    """ Returns the MAC address of a network host, requires >= WIN2K.
    """

    # Check for api availability
    try:
    SendARP = ctypes.windll.I phlpapi.SendARP
    except:
    raise NotImplementedE rror('Usage only on Windows 2000 and
    above')

    # Doesn't work with loopbacks, but let's try and help.
    if host == '127.0.0.1' or host.lower() == 'localhost':
    host = socket.gethostn ame()

    # gethostbyname blocks, so use it wisely.
    try:
    inetaddr = ctypes.windll.w sock32.inet_add r(host)
    if inetaddr in (0, -1):
    raise Exception
    except:
    hostip = socket.gethostb yname(host)
    inetaddr = ctypes.windll.w sock32.inet_add r(hostip)

    buffer = ctypes.c_buffer (6)
    addlen = ctypes.c_ulong( ctypes.sizeof(b uffer))
    if SendARP(inetadd r, 0, ctypes.byref(bu ffer), ctypes.byref(ad dlen))
    != 0:
    raise WindowsError('R etreival of mac address(%s) - failed' %
    host)

    # Convert binary data into a string.
    macaddr = ''
    for intval in struct.unpack(' BBBBBB', buffer):
    if intval > 15:
    replacestr = '0x'
    else:
    replacestr = 'x'
    macaddr = ''.join([macaddr, hex(intval).rep lace(replacestr ,
    '')])

    return macaddr.upper()

    if __name__ == '__main__':
    print 'Your mac address is %s' % get_macaddress( 'localhost')

    It works perfect under W2K and above. But I would like to run it on
    Win98 too. Any help?

    Thanks

    Daniel

  • Scott David Daniels

    #2
    Re: How to get the local mac address?

    Daniel Crespo wrote:[color=blue]
    > Hi, I tried: ...[/color]
    [color=blue]
    > # Convert binary data into a string.
    > macaddr = ''
    > for intval in struct.unpack(' BBBBBB', buffer):
    > if intval > 15:
    > replacestr = '0x'
    > else:
    > replacestr = 'x'
    > macaddr = ''.join([macaddr, hex(intval).rep lace(replacestr , '')])[/color]

    Replace the above by:
    return '%02X' * 6 % struct.unpack(' BBBBBB', buffer)

    (doesn't help with win98, though)

    --
    -Scott David Daniels
    scott.daniels@a cm.org

    Comment

    • Daniel Crespo

      #3
      Re: How to get the local mac address?

      Hi, Scott,

      Thanks for your answer
      [color=blue][color=green]
      >> Hi, I tried: ...
      >> # Convert binary data into a string.
      >> macaddr = ''
      >> for intval in struct.unpack(' BBBBBB', buffer):
      >> if intval > 15:
      >> replacestr = '0x'
      >> else:
      >> replacestr = 'x'
      >> macaddr = ''.join([macaddr, hex(intval).rep lace(replacestr , '')])[/color]
      >
      >
      >Replace the above by:
      > return '%02X' * 6 % struct.unpack(' BBBBBB', buffer)[/color]

      Replace all the above? I mean all this:

      # Convert binary data into a string.
      macaddr = ''
      for intval in struct.unpack(' BBBBBB', buffer):
      if intval > 15:
      replacestr = '0x'
      else:
      replacestr = 'x'
      macaddr = ''.join([macaddr, hex(intval).rep lace(replacestr ,
      '')])

      ?
      [color=blue]
      >(doesn't help with win98, though)[/color]

      Sorry, but I don't understand... I would like it to get running on
      Win98. I know I have to change some code here, but don't know what :(

      Comment

      • bonono@gmail.com

        #4
        Re: How to get the local mac address?


        Daniel Crespo wrote:[color=blue]
        > Hi, I tried:
        >
        > import ctypes
        > import socket
        > import struct
        >
        > def get_macaddress( host):
        > """ Returns the MAC address of a network host, requires >= WIN2K.
        > """
        >
        > # Check for api availability
        > try:
        > SendARP = ctypes.windll.I phlpapi.SendARP
        > except:
        > raise NotImplementedE rror('Usage only on Windows 2000 and
        > above')
        >
        > # Doesn't work with loopbacks, but let's try and help.
        > if host == '127.0.0.1' or host.lower() == 'localhost':
        > host = socket.gethostn ame()
        >
        > # gethostbyname blocks, so use it wisely.
        > try:
        > inetaddr = ctypes.windll.w sock32.inet_add r(host)
        > if inetaddr in (0, -1):
        > raise Exception
        > except:
        > hostip = socket.gethostb yname(host)
        > inetaddr = ctypes.windll.w sock32.inet_add r(hostip)
        >
        > buffer = ctypes.c_buffer (6)
        > addlen = ctypes.c_ulong( ctypes.sizeof(b uffer))
        > if SendARP(inetadd r, 0, ctypes.byref(bu ffer), ctypes.byref(ad dlen))
        > != 0:
        > raise WindowsError('R etreival of mac address(%s) - failed' %
        > host)
        >
        > # Convert binary data into a string.
        > macaddr = ''
        > for intval in struct.unpack(' BBBBBB', buffer):
        > if intval > 15:
        > replacestr = '0x'
        > else:
        > replacestr = 'x'
        > macaddr = ''.join([macaddr, hex(intval).rep lace(replacestr ,
        > '')])
        >
        > return macaddr.upper()
        >
        > if __name__ == '__main__':
        > print 'Your mac address is %s' % get_macaddress( 'localhost')
        >
        > It works perfect under W2K and above. But I would like to run it on
        > Win98 too. Any help?
        >[/color]
        Sorry that I can't help you in any way but have a question myself. Is
        there an OS independent way to get this thing(regardles s of how to
        format it) in Python ? I know this may not matter if all you want is
        Windows but there is just another thread talking about one should write
        programs that is OS independent.

        Is this a problem of the network library of python ?

        Comment

        • Frank Millman

          #5
          Re: How to get the local mac address?


          bonono@gmail.co m wrote:[color=blue]
          > Sorry that I can't help you in any way but have a question myself. Is
          > there an OS independent way to get this thing(regardles s of how to
          > format it) in Python ? I know this may not matter if all you want is
          > Windows but there is just another thread talking about one should write
          > programs that is OS independent.
          >
          > Is this a problem of the network library of python ?[/color]

          This is not a generic solution, but it works for me on Linux and
          Windows

          def getMacAddress() :
          if sys.platform == 'win32':
          for line in os.popen("ipcon fig /all"):
          if line.lstrip().s tartswith('Phys ical Address'):
          mac = line.split(':')[1].strip().replac e('-',':')
          break
          else:
          for line in os.popen("/sbin/ifconfig"):
          if line.find('Ethe r') > -1:
          mac = line.split()[4]
          break
          return mac

          HTH

          Frank Millman

          Comment

          • bonono@gmail.com

            #6
            Re: How to get the local mac address?


            Frank Millman wrote:[color=blue]
            > bonono@gmail.co m wrote:[color=green]
            > > Sorry that I can't help you in any way but have a question myself. Is
            > > there an OS independent way to get this thing(regardles s of how to
            > > format it) in Python ? I know this may not matter if all you want is
            > > Windows but there is just another thread talking about one should write
            > > programs that is OS independent.
            > >
            > > Is this a problem of the network library of python ?[/color]
            >
            > This is not a generic solution, but it works for me on Linux and
            > Windows
            >
            > def getMacAddress() :
            > if sys.platform == 'win32':
            > for line in os.popen("ipcon fig /all"):
            > if line.lstrip().s tartswith('Phys ical Address'):
            > mac = line.split(':')[1].strip().replac e('-',':')
            > break
            > else:
            > for line in os.popen("/sbin/ifconfig"):
            > if line.find('Ethe r') > -1:
            > mac = line.split()[4]
            > break
            > return mac
            >[/color]
            Thanks, but how can I associate the result to the socket, assuming that
            is the reason for wanting to get at the MAC ?

            I see that some *nix implementation use fcntl/ioctl to read this info
            out of the file handle of a socket but these modules don't exist on
            Windows(may be some other platform as well).

            Comment

            • Frank Millman

              #7
              Re: How to get the local mac address?


              bonono@gmail.co m wrote:[color=blue]
              > Frank Millman wrote:[color=green]
              > > bonono@gmail.co m wrote:[color=darkred]
              > > > Sorry that I can't help you in any way but have a question myself. Is
              > > > there an OS independent way to get this thing(regardles s of how to
              > > > format it) in Python ? I know this may not matter if all you want is
              > > > Windows but there is just another thread talking about one should write
              > > > programs that is OS independent.
              > > >
              > > > Is this a problem of the network library of python ?[/color]
              > >
              > > This is not a generic solution, but it works for me on Linux and
              > > Windows
              > >
              > > def getMacAddress() :
              > > if sys.platform == 'win32':
              > > for line in os.popen("ipcon fig /all"):
              > > if line.lstrip().s tartswith('Phys ical Address'):
              > > mac = line.split(':')[1].strip().replac e('-',':')
              > > break
              > > else:
              > > for line in os.popen("/sbin/ifconfig"):
              > > if line.find('Ethe r') > -1:
              > > mac = line.split()[4]
              > > break
              > > return mac
              > >[/color]
              > Thanks, but how can I associate the result to the socket, assuming that
              > is the reason for wanting to get at the MAC ?
              >
              > I see that some *nix implementation use fcntl/ioctl to read this info
              > out of the file handle of a socket but these modules don't exist on
              > Windows(may be some other platform as well).[/color]

              As you can see, this is a quick and dirty solution.

              I am sure you can hack at it some more, bring up the associated ip
              address, and compare it with socket.gethostb yaddr() or similar.

              I don't know of a more correct solution - maybe someone else can advise
              better.

              BTW I recall a response some time ago warning that you cannot rely on a
              mac address, as they can be modified. Depending on your intended use,
              this may or may not be important.

              Sorry I cannot be of more help

              Frank

              Comment

              • Steve Holden

                #8
                Re: How to get the local mac address?

                bonono@gmail.co m wrote:[color=blue]
                > Frank Millman wrote:
                >[color=green]
                >>bonono@gmail. com wrote:
                >>[color=darkred]
                >>>Sorry that I can't help you in any way but have a question myself. Is
                >>>there an OS independent way to get this thing(regardles s of how to
                >>>format it) in Python ? I know this may not matter if all you want is
                >>>Windows but there is just another thread talking about one should write
                >>>programs that is OS independent.
                >>>
                >>>Is this a problem of the network library of python ?[/color]
                >>
                >>This is not a generic solution, but it works for me on Linux and
                >>Windows
                >>
                >>def getMacAddress() :
                >> if sys.platform == 'win32':
                >> for line in os.popen("ipcon fig /all"):
                >> if line.lstrip().s tartswith('Phys ical Address'):
                >> mac = line.split(':')[1].strip().replac e('-',':')
                >> break
                >> else:
                >> for line in os.popen("/sbin/ifconfig"):
                >> if line.find('Ethe r') > -1:
                >> mac = line.split()[4]
                >> break
                >> return mac
                >>[/color]
                >
                > Thanks, but how can I associate the result to the socket, assuming that
                > is the reason for wanting to get at the MAC ?
                >[/color]
                Why should you want to associate a MAC address with a socket? Each
                interface has an IP address, and it's that you should be using.
                [color=blue]
                > I see that some *nix implementation use fcntl/ioctl to read this info
                > out of the file handle of a socket but these modules don't exist on
                > Windows(may be some other platform as well).
                >[/color]
                Indeed, and that's why most networkers probably wouldn't regard this as
                a deficiency in Python's network handling but an inevitable consequence
                of the diversity of architectures, utilities and drivers in today's world.

                It may well be possible to write Python code that will run on all
                platforms (for example, the same way as the os.path module does, by
                importing the correct piece of code according to the platform), but it
                would need maintenance. Since the interface MAC address is unimportant
                for most network applications I guess nobody has so far thought it worth
                contributing to the core.

                regards
                Steve
                --
                Steve Holden +44 150 684 7255 +1 800 494 3119
                Holden Web LLC www.holdenweb.com
                PyCon TX 2006 www.python.org/pycon/

                Comment

                • bonono@gmail.com

                  #9
                  Re: How to get the local mac address?


                  Steve Holden wrote:[color=blue]
                  > Why should you want to associate a MAC address with a socket? Each
                  > interface has an IP address, and it's that you should be using.[/color]
                  Say for example I want to find out the MAC if a particular interface in
                  python.
                  [color=blue]
                  > It may well be possible to write Python code that will run on all
                  > platforms (for example, the same way as the os.path module does, by
                  > importing the correct piece of code according to the platform), but it
                  > would need maintenance. Since the interface MAC address is unimportant
                  > for most network applications I guess nobody has so far thought it worth
                  > contributing to the core.
                  >[/color]
                  That is a reasonable explanation.

                  Comment

                  • Steve Holden

                    #10
                    Re: How to get the local mac address?

                    bonono@gmail.co m wrote:[color=blue]
                    > Steve Holden wrote:
                    >[color=green]
                    >>Why should you want to associate a MAC address with a socket? Each
                    >>interface has an IP address, and it's that you should be using.[/color]
                    >
                    > Say for example I want to find out the MAC if a particular interface in
                    > python.
                    >[/color]
                    When you are asked "why would you want to do something" it isn't
                    normally considered sufficient to reply "suppose I want to do
                    something". I'm still trying to find out what use case (apart from
                    curiosity) drives this need to know.

                    regards
                    Steve
                    --
                    Steve Holden +44 150 684 7255 +1 800 494 3119
                    Holden Web LLC www.holdenweb.com
                    PyCon TX 2006 www.python.org/pycon/

                    Comment

                    • bonono@gmail.com

                      #11
                      Re: How to get the local mac address?


                      Steve Holden wrote:[color=blue]
                      > bonono@gmail.co m wrote:[color=green]
                      > > Steve Holden wrote:
                      > >[color=darkred]
                      > >>Why should you want to associate a MAC address with a socket? Each
                      > >>interface has an IP address, and it's that you should be using.[/color]
                      > >
                      > > Say for example I want to find out the MAC if a particular interface in
                      > > python.
                      > >[/color]
                      > When you are asked "why would you want to do something" it isn't
                      > normally considered sufficient to reply "suppose I want to do
                      > something". I'm still trying to find out what use case (apart from
                      > curiosity) drives this need to know.
                      >[/color]
                      That is nothing but curiosity of why there is no such thing. I didn't
                      start a thread with "what the xyz@!% hell that I cannot get MAC address
                      through the socket module".

                      And I answer things the way I want to, if it does fit your expected
                      answer, there is nothing I can do. I am not here to convince you.

                      Comment

                      • Steve Holden

                        #12
                        Re: How to get the local mac address?

                        bonono@gmail.co m wrote:[color=blue]
                        > Steve Holden wrote:
                        >[color=green]
                        >>bonono@gmail. com wrote:
                        >>[color=darkred]
                        >>>Steve Holden wrote:
                        >>>
                        >>>
                        >>>>Why should you want to associate a MAC address with a socket? Each
                        >>>>interface has an IP address, and it's that you should be using.
                        >>>
                        >>>Say for example I want to find out the MAC if a particular interface in
                        >>>python.
                        >>>[/color]
                        >>
                        >>When you are asked "why would you want to do something" it isn't
                        >>normally considered sufficient to reply "suppose I want to do
                        >>something". I'm still trying to find out what use case (apart from
                        >>curiosity) drives this need to know.
                        >>[/color]
                        >
                        > That is nothing but curiosity of why there is no such thing. I didn't
                        > start a thread with "what the xyz@!% hell that I cannot get MAC address
                        > through the socket module".
                        >
                        > And I answer things the way I want to, if it does fit your expected
                        > answer, there is nothing I can do. I am not here to convince you.
                        >[/color]
                        Temper, temper.

                        regards
                        Steve
                        --
                        Steve Holden +44 150 684 7255 +1 800 494 3119
                        Holden Web LLC www.holdenweb.com
                        PyCon TX 2006 www.python.org/pycon/

                        Comment

                        • bonono@gmail.com

                          #13
                          Re: How to get the local mac address?


                          Steve Holden wrote:[color=blue]
                          > bonono@gmail.co m wrote:[color=green]
                          > > Steve Holden wrote:
                          > >[color=darkred]
                          > >>bonono@gmail. com wrote:
                          > >>
                          > >>>Steve Holden wrote:
                          > >>>
                          > >>>
                          > >>>>Why should you want to associate a MAC address with a socket? Each
                          > >>>>interface has an IP address, and it's that you should be using.
                          > >>>
                          > >>>Say for example I want to find out the MAC if a particular interface in
                          > >>>python.
                          > >>>
                          > >>
                          > >>When you are asked "why would you want to do something" it isn't
                          > >>normally considered sufficient to reply "suppose I want to do
                          > >>something". I'm still trying to find out what use case (apart from
                          > >>curiosity) drives this need to know.
                          > >>[/color]
                          > >
                          > > That is nothing but curiosity of why there is no such thing. I didn't
                          > > start a thread with "what the xyz@!% hell that I cannot get MAC address
                          > > through the socket module".
                          > >
                          > > And I answer things the way I want to, if it does fit your expected
                          > > answer, there is nothing I can do. I am not here to convince you.
                          > >[/color]
                          > Temper, temper.
                          >[/color]
                          you can read my temper from what I write ?

                          Comment

                          • Steve Holden

                            #14
                            Re: How to get the local mac address?

                            bonono@gmail.co m wrote:[color=blue]
                            > Steve Holden wrote:
                            >[color=green]
                            >>bonono@gmail. com wrote:
                            >>[color=darkred]
                            >>>Steve Holden wrote:
                            >>>
                            >>>
                            >>>>bonono@gmai l.com wrote:
                            >>>>
                            >>>>
                            >>>>>Steve Holden wrote:
                            >>>>>
                            >>>>>
                            >>>>>
                            >>>>>>Why should you want to associate a MAC address with a socket? Each
                            >>>>>>interfa ce has an IP address, and it's that you should be using.
                            >>>>>
                            >>>>>Say for example I want to find out the MAC if a particular interface in
                            >>>>>python.
                            >>>>>
                            >>>>
                            >>>>When you are asked "why would you want to do something" it isn't
                            >>>>normally considered sufficient to reply "suppose I want to do
                            >>>>something ". I'm still trying to find out what use case (apart from
                            >>>>curiosity ) drives this need to know.
                            >>>>
                            >>>
                            >>>That is nothing but curiosity of why there is no such thing. I didn't
                            >>>start a thread with "what the xyz@!% hell that I cannot get MAC address
                            >>>through the socket module".
                            >>>
                            >>>And I answer things the way I want to, if it does fit your expected
                            >>>answer, there is nothing I can do. I am not here to convince you.
                            >>>[/color]
                            >>
                            >>Temper, temper.
                            >>[/color]
                            >
                            > you can read my temper from what I write ?
                            >[/color]
                            Nope, but I can make inferences, whose correctness you can choose to lie
                            or tell the truth about. I was merely trying to make the point that your
                            response failed to further anybody's understanding of anything. I'm not
                            really bothered *why* you do what you do.

                            I asked "Why should you want to associate a MAC address with a socket?"
                            and you replied "Say for example I want to find out the MAC if a
                            particular interface in python". Fine. But if you don't want to engage
                            in a dialogue, why bother posting at all?

                            regards
                            Steve
                            --
                            Steve Holden +44 150 684 7255 +1 800 494 3119
                            Holden Web LLC www.holdenweb.com
                            PyCon TX 2006 www.python.org/pycon/

                            Comment

                            • bonono@gmail.com

                              #15
                              Re: How to get the local mac address?


                              Steve Holden wrote:[color=blue]
                              > Nope, but I can make inferences, whose correctness you can choose to lie
                              > or tell the truth about. I was merely trying to make the point that your
                              > response failed to further anybody's understanding of anything. I'm not
                              > really bothered *why* you do what you do.[/color]
                              That is nice try. I said I am not, you can fit it as "I am lying". As
                              for failed or not failed, I don't know what anybody want to get out of
                              it. I just curious why there is no such function in the socket model,
                              when I saw a "OS dependent" implementation of getting MAC. Nothing
                              more. And your answer that there is not sufficient need for putting it
                              in the standard libary(for the maintainance work needed), answered my
                              puzzle.
                              [color=blue]
                              >
                              > I asked "Why should you want to associate a MAC address with a socket?"
                              > and you replied "Say for example I want to find out the MAC if a
                              > particular interface in python". Fine. But if you don't want to engage
                              > in a dialogue, why bother posting at all?[/color]
                              Huh ? You ask why, I come up with an example. I said it all started
                              with curiosity, not out of need. I don't see why it is not a dialogue.
                              You think that it is not because it doesn't meet your expectation
                              answer(thus your "you are supposed" response), that I can do nothing as
                              that is your right or thought.

                              Comment

                              Working...