Development

NAVIGATION
CATEGORIES
REFERRENCE
LINKS
  • newbe: tuple

    1 answers - 474 bytes - related search similar search Add To My Delicious Add To My Stumble Upon Add To My Google Mark Add To My Facebook Add To My Digg Add To My Reddit

    I am trying to get my ip address through a script and I am using the
    following code:
    import socket
    ip = socket.gethostbyaddr(socket.gethostname())
    ip then becomes a tuple and takes on three values. I am trying to pull the
    value of ip[2] which when printed displays:
    ['10.5.100.17'].
    I want this ip that is being returned, but I would like it as a string,
    without the [' and ']. Any idea how I would trim this down?
  • No.1 | | 1373 bytes | |

    ip = socket.gethostbyaddr(socket.gethostname())

    ip then becomes a tuple and takes on three values. I am trying to pull the
    value of ip[2] which when printed displays:
    ['10.5.100.17'].

    I want this ip that is being returned, but I would like it as a string,
    without the [' and ']. Any idea how I would trim this down?

    Well, what you're getting back is the list of possible IP
    addresses for your machine. The "['w.x.y.z']" is simply the
    repr() of that list. A single machine can have multiple IP
    addresses, so ip[2] returns them as a list. You can either use

    ip_addresses = ip[2]
    my_ip_address = ip_addresses[0]
    # this is the same as
    # my_ip_address = ip[2][0]
    # only slightly clearer to read

    or your code can graciously accomodate them the way they were
    designed for:

    for ip_address in ip_addresses:
    print ip_address

    This allows you to deal with the possibility that the machine has
    more than one IP address assigned to it. I'm not at my BSD
    box, but it's got at least three interfaces in it, and each one
    has its own IP address assigned to it. I presume that ip[2]
    would return a list of three strings in its case, something like

    ['192.168.3.14', '10.3.14.15', '172.16.3.14']

    HTH,
    -tkc

Re: newbe: tuple


max 4000 letters.
Your nickname that display:
In order to stop the spam: 9 + 8 =
QUESTION ON "Development"

EMSDN.COM