Windows getting local ip address

S

SolaFide

On Linux, it is a simple matter to get the local ip address with
system.os("ifconfig >> /tmp/ip"); ip=open("/tmp/ip").readlines(), etc.
How can I do this with Windows?
 
U

utabintarbo

You can do essentially the same thing substituting "ipconfig" for
ifconfig.

Though I am sure there are better ways....
 
F

Fredrik Lundh

SolaFide said:
On Linux, it is a simple matter to get the local ip address with
system.os("ifconfig >> /tmp/ip"); ip=open("/tmp/ip").readlines(), etc.

ip = os.popen("ifconfig").readlines()

is a bit more convenient.
How can I do this with Windows?

the command is called "ipconfig" in windows.

there's also
>>> import socket
>>> socket.gethostbyname(socket.gethostname()) '1.2.3.4'
>>> socket.gethostbyname_ex(socket.gethostname()) ('bender.shiny.com', ['bender'], ['1.2.3.4'])
>>> socket.getaddrinfo(socket.gethostname(), 0)
[(2, 1, 0, '', ('1.2.3.4', 0)), (2, 2, 0, '', ('1.2.3.4', 0))]

etc. if you're behind a firewall/NAT etc and you want your "public IP",
you can do something like:
'4.3.2.1'

hope this helps!

</F>
 
A

Arne Ludwig

The second solution can give really weird results though, e.g. on my
Linux system I get:
('linux.site', ['linux'], ['127.0.0.2'])

A more flexible but potentially unportable way would be:
.... s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
.... return socket.inet_ntoa(fcntl.ioctl(
.... s.fileno(),
.... 0x8915, # SIOCGIFADDR
.... struct.pack('256s', ifname[:15])
.... )[20:24])
....'192.168.0.174'
 
E

Erno Kuusela

The traditional right way (tm) to do this is to call getsockname() on
the (a?) socket that's connected to the guy you want to tell your
address to. This picks the right address in case you have several. If
you don't have a socket handy, you can make a connectionless UDP
socket and connect() it to a suitable place - this won't result in any
packets on the wire. NAT breaks it of course, but then you couldn't
easily be contacted from outside the NAT anyway.

-- erno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top