LoginSignup
8
7

More than 5 years have passed since last update.

ハイフン区切り形式の MAC アドレスを取得する -1 liner 編-

Last updated at Posted at 2012-10-05

一応 uuid.getnode() を使えば MAC アドレスは取得できますが、結果は 48bits の 10 進整数です。
ifconfig や getmac コマンドの XX-XX-XX-XX-XX-XX という
ヒューマンリーダブルな形式で表示したい!というわけで作ってみました。

getmac.py
import struct, sys, uuid; sys.stdout.write( "-".join( [hex( fragment )[2:].zfill( 2 ) for fragment in struct.unpack( "BBBBBB", struct.pack( "!Q", uuid.getnode() )[2:] )] ) + "\n" )

確認してみましょう。
まずは getmac の出力です。
(プロンプトがしょんぼりしているのは仕様です。突っ込まないでください)

(´・ω・`)o( getmac

物理アドレス        トランスポート名
=================== ==========================================================
00-25-22-E0-A0-F5   \Device\Tcpip_{0C99CB65-8BF1-4AE6-AD00-8A3D7369C745}

では次に getmac.py を実行してみます。

(´・ω・`)o( getmac.py
00-25-22-e0-a0-f5

アルファベットが大文字か小文字かの違いはありますが、
MAC アドレスとしては同じ値が得られました。

なお、PYTHONSTARTUP で読み込むファイルに次のコードを追加しておくと
Python インタラクティブシェルの中で getmac() 一発で取得できるようになります。

startup.py
import struct
import uuid
getmac = lambda : "-".join( [hex( fragment )[2:].zfill( 2 ) for fragment in struct.unpack( "BBBBBB", struct.pack( "!Q", uuid.getnode() )[2:] )] )

2012-10-03 16:40
print 文だと Python 3.x 系で動作しないため修正しました。

2012-10-04 10:58
Python 3.x 系だと string モジュールに zfill がないので修正しました。
互換性を大きく損なう仕様変更は、本当に勘弁してもらいたいものです。

8
7
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7