Tuesday, September 1, 2015

Python Socket - Some useful Functions

 I have shown you how to write basic socket programming and also how to create a simple client-server model for socket programming in my website http://pythonbeginner.in/socket-programming-in-python.
Now lets see some of the common socket modules which we skip sometimes but they are useful enough. One of them is socket.gethostbyname(). -  this particular function will give us the ip address of a domain name. Lets see by an example  -

>>> import socket
>>>print (socket.gethostbyname("www.google.com"))
216.58.196.100

So, if you want to know the ip address of a certain domain, you can always try this option.

Other function is the opposite of this function; socket.gethostbyaddr() will give us the domain name of a ip address (if domain to ip map is available). Lets see that through an example  -

>>> print (socket.gethostbyaddr(216.58.196.100))
('maa03s19-in-f4.1e100.net', ['maa03s19-in-f100.1e100.net'], ['216.58.196.100'])


Now if you want to see the name of the domain and the port together you can use this  -

>>>   print (socket.getnameinfo(('216.58.196.100',80),0))
('maa03s19-in-f4.1e100.net', 'http')
You can change the value of 0 in the second element of the passed tuple and see what happens.

No comments:

Post a Comment

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...