473,591 Members | 2,783 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Dec 14 '05 #1
24 7299
Daniel Crespo wrote:
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 , '')])


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

(doesn't help with win98, though)

--
-Scott David Daniels
sc***********@a cm.org
Dec 14 '05 #2
Hi, Scott,

Thanks for your answer
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 , '')])

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


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 ,
'')])

?
(doesn't help with win98, though)


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 :(

Dec 14 '05 #3

Daniel Crespo wrote:
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?

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 ?

Dec 15 '05 #4

bo****@gmail.co m wrote:
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 ?


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

Dec 15 '05 #5

Frank Millman wrote:
bo****@gmail.co m wrote:
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 ?


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

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).

Dec 15 '05 #6

bo****@gmail.co m wrote:
Frank Millman wrote:
bo****@gmail.co m wrote:
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 ?


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

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).


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

Dec 15 '05 #7
bo****@gmail.co m wrote:
Frank Millman wrote:
bo****@gmail. com wrote:
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 ?
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


Thanks, but how can I associate the result to the socket, assuming that
is the reason for wanting to get at the MAC ?

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.
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).

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/

Dec 15 '05 #8

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.
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.

That is a reasonable explanation.

Dec 15 '05 #9
bo****@gmail.co m 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.

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/

Dec 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
10901
by: crypto_stonelock | last post by:
Hello, I was wondering if anybody knew how to retrieve the IP address attributed dynamically by your ISP without having to use the info collected on a socket with say .getLocalAddress. I'm using dsl with PPPoE and whenever i try to get the local address, through InetAddress, the network address is returned. So i'm guessing that InetAddress is out.My network is in the way and i don't think i can really go around it. I can't seem to...
7
17940
by: gurtd_dauberie | last post by:
I can't get the correct IP address on Linux... The following code works properly on Windows and Unix. But on Linux, I always get the Loopback Address (127.0.0.1) Here is the code : //gets the IP via InetAddress class //works on UNIX and WIN, but not on LINUX !! InetAddress hostIP = InetAddress.getLocalHost(); String hostIPStr = hostIP.getHostAddress();
21
15683
by: Alexander N. Spitzer | last post by:
If I have a machine with 3 virtual IP addresses (192.168.1.), how can I start 3 instances of the same RMI application (each started with different properties/configs), each listening on the port 1234, but each instance binds to a different ip address. that is to say: instance #1 binds to 192.168.1.5/port 1234 instance #2 binds to 192.168.1.6/port 1234 instance #3 binds to 192.168.1.7/port 1234
2
6463
by: Keith Langer | last post by:
I have a TCPListener which needs to listen on my LAN IP as well as the loopback address. In VS.Net 2002 the TCPListener constructor could accept the port as an argument and it automatically bound to all network adapters (this is also how it worked with VB6). Now that constructor is obsolete, and the new one requires an IPEndPoint or IPAddress. How could I listen on the same port on all network adapters using VS.Net 2003? I'd rather...
2
1881
by: Sherif ElMetainy | last post by:
Hello I am writing a HTTP client, that will run on a computer with multiple IP addresses. I want to bind the TCP socket for the HTTP connection to a specific IP address, but unfortunately there is no option to do this in System.Net.HttpWebRequest class. I looked for that option a lot, I even looked at the ROTOR source code to if there is a private member that I can access with reflection but didn't find anything. (I know this is not...
0
3015
by: Gregory Hassett | last post by:
Hello, I want to periodically send a TCP packet to a peer, always from the same source port. That is, each packet will come from my local ip address, port 8801, and go to the peer's ip address, to HIS port 8801. This means that I need to bind my sender socket to (myaddress,8801), use it for the send, then shut it down and close it. Then I want to wait, say 30 seconds, and do it all over again. Naturally, the socket's ReuseAddress...
2
1886
by: Code Monkey | last post by:
Hope someone can help me out here. I'm writing some code (web forms) to see where a specific domain name resolves and if its not a local address, redirect to a specific redirect page. <code> IPHostEntry IPHost = Dns.Resolve("www.domainname.com");
0
1702
by: Michael Höhne | last post by:
Hi, we're developing some web services and use the local development server of Visual Studio 2005 to create, run and debug the project. The web service methods connect to a database hosted on a dedicated server and the Microsoft CRM 3.0 server, also on a separate machine. As the CRM server installation makes changes to the Active Directory, they are located in a separate domain, while the development machines are member of the companies...
5
20131
by: ljlevend2 | last post by:
Is there any way to create a local server during runtime? For example, if you add an existing Web Site to a Solution from within Visual Studio (by right clicking the solution in the Solution Explorer, then selecting Add - Existing Web Site...), then Visual Studio will create an ASP.NET Development Server on a random port (e.g., http://localhost:1619/Test). Can a similar thing be done during runtime with VB.NET? If not, is it possible to...
5
3726
by: Eng Teng | last post by:
What is the command to display computer name & ip address in VB.NET 2005 (OS WindowsXP & Windows Vista) Regards, Tee
0
7934
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7870
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8236
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
7992
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8225
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5400
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3891
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2378
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1199
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.