-3

I was going through socket programming in python and I saw this :

sock.getsockname()[1] , can anyone please explain what is that "[1]" for ?

Mazhar MIK
  • 792
  • 9
  • 12

3 Answers3

5
>>> sock.getsockname()
('0.0.0.0', 0)

The first element of the returned tuple (it is a wird kind of array) sock.getsockname()[0] is the IP, the second one sock.getsockname()[1] the port.

tuple[index] gets the object at this index in the tuple

0

sock.getsocketname() function returns array and [1] immediatelly returns you [1] of that array.

variable = sock.getsocketname()[1]

is equivalent to

arr = sock.getsocketname()
variable = arr[1]

In your case, this is socket port number.

tilz0R
  • 6,949
  • 2
  • 21
  • 37
0

[1] is how you access to the second element of a list (first element will be [0]).

my_list = ["a", "b", "c"]
print my_list[1] # => "b"

Because sock.getsocketname() returns tuple, you access to the second element like it.

A mock showing the exact same behaviour:

def foo():
    return ("a", "b", "c")
print foo()[1] # => "b"
Arount
  • 8,960
  • 1
  • 27
  • 40