Get local IPv4 and IPv6 using python raw socket

Namaste Friends,



Today, In this post I am going to share with you a small piece of code that can help you in finding your host computer IPv4 and IPv6 also.


Introduction


Well, There are various reasons in which we need to find the exact IPv4 Or IPv6 of our host computer to do any specific work and at that time, This Piece of codes is really going to help you. Actually, we going to create 2 functions, the first function to find IPv4 and second one is to find IPv6.

How it's going to work


basically, we just going to make a raw socket object then, we need to force our socket object to find our host computer IP address. To force our socket object, we just need to make a connection with any IP address (Dead IP will also work). After That, We just need to another function that will help us to get our socket object information like IP address



Simplest Form Of Codes For IPv4


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

Explanation



  • line 2, To make a socket Object
  • line 5, To bind it
  • line 6, Get Socket Info
  • line 10, Close it


Simplest Form Of Codes For IPv6




1
2
3
4
5
6
7
8
9
def get_ipv6():
    s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)

    s.connect(('2001:0db8:85a3:0000:0000:8a2e:0370:7334', 1))

    ip = s.getsockname()[0]

    s.close()
    return ip

Explanation



  • line 2, To make a socket object
  • line 4, To bind it
  • line 6, Get socket info
  • line 8, Close socket


Final Codes


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import socket
from binascii import hexlify




def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

def get_ipv6():
    s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)

    s.connect(('2001:0db8:85a3:0000:0000:8a2e:0370:7334', 1))

    ip = s.getsockname()[0]

    s.close()
    return ip

if __name__ == '__main__':
    print get_ip()
    print get_ipv6(



This Tutorial Ends Here.

I hope you all are enjoying.

Share this

Related Posts

Previous
Next Post »