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.

how to get interface card names using python socket

Namaste Friends,





Today, I am going to share with you simple python codes, which can enumerate available interface name.



Introduction


To make a connection in a computer, first we have to choose a Network Interface from available source and at that time, This automatic function can help you to find the available Interface name so, that you can proceed further.


Before Sharing This Codes, I want to clear that These codes are not written by me.


 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
32
33
34
35
36
37
38
39
40
41
import socket
import fcntl
import struct
import array


# # found on <http://code.activestate.com/recipes/439093/#c1>
# get all interface names
def all_interfaces():
    max_possible = 128  # arbitrary. raise if needed.

    bytes = max_possible * 32

    # Create a dummy socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


    names = array.array('B', '\0' * bytes)

    outbytes = struct.unpack('iL', fcntl.ioctl(
        s.fileno(),
        0x8912,  # SIOCGIFCONF
        struct.pack('iL', bytes, names.buffer_info()[0])
    ))[0]

    namestr = names.tostring()

    lst = []

    for i in range(0, outbytes, 40):
        name = namestr[i:i+16].split('\0', 1)[0]
        ip   = namestr[i+20:i+24]
        lst.append((name, socket.inet_ntoa(ip)))

    s.close()
    return lst



if __name__ == '__main__':
    print all_interfaces()


Credit Link: http://code.activestate.com/recipes/439093/


Code to ping request using raw python socket

Namaste Friends,




Today, In this tutorial I am going to tell you about how you can create a simple ping script using python raw sockets.


Introduction


Ping is a simple concept to find and ensure that a host computer or device the user wants to connect is actually working and available on users network. In simple words, With the help of ping request, a user can find available and operate IP address on to its network. Ping works by Sending ICMP packet on any specific network interface and wait for its reply. ICMP stands for Internet control message protocol.

Click here to read more.



Requirement


  • Python 2.x Or 3.x
  • ICMP packet script (Click here)
  • Root Permission to run it



Simplest Function To Send Ping Request (Click here For ICMPPacket Function)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#  
def single_ping_request(s, addr=None):

    # Random Packet Id
    pkt_id = random.randrange(10000,65000)
    
    # Create ICMP Packet
    packet = ICMPPacket(icmp_id=pkt_id).raw

    # Send ICMP Packet
    while packet:
        sent = s.sendto(packet, (addr, 1))
        packet = packet[sent:]

    return pkt_id

Explanation



  • line 5, To choice Random Integer For Identification
  • line 7, To make a raw ICMP packet bytes
  • line 12, To send Packet




Simplest Function To Receive Ping Reply (Click here For ICMPPacket Function)


 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
def catch_ping_reply(s, ID, time_sent, timeout=1):

    # create while loop
    while True:
        starting_time = time.time()     # Record Starting Time

        # to handle timeout function of socket
        process = select.select([s], [], [], timeout)
        
        # check if timeout
        if process[0] == []:
            return

        # receive packet
        rec_packet, addr = s.recvfrom(1024)

        # extract icmp packet from received packet 
        icmp = rec_packet[20:28]

        # extract information from icmp packet
        _id = ext_icmp_header(icmp)['id']

        # check identification
        if _id == ID:
            return ext_icmp_header(icmp)
    return

Explanation



  • line 5, To Record Current Time
  • line 8, To Handle socket timeout function
  • line 11, To Check Function Timeout status
  • line 15, To capture packet
  • line 18, To Extract ICMP header From Complete Packet
  • line 21, To Decode ICMP header
  • line 24, Verify ICMP packet reply




Complete Codes (Click here For ICMPPacket Function)




 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# import module
import socket
import os
import random
import time
import select
from ICMP import ICMPPacket, ext_icmp_header



def catch_ping_reply(s, ID, time_sent, timeout=1):

    # create while loop
    while True:
        starting_time = time.time()     # Record Starting Time

        # to handle timeout function of socket
        process = select.select([s], [], [], timeout)
        
        # check if timeout
        if process[0] == []:
            return

        # receive packet
        rec_packet, addr = s.recvfrom(1024)

        # extract icmp packet from received packet 
        icmp = rec_packet[20:28]

        # extract information from icmp packet
        _id = ext_icmp_header(icmp)['id']

        # check identification
        if _id == ID:
            return ext_icmp_header(icmp)
    return


#  
def single_ping_request(s, addr=None):

    # Random Packet Id
    pkt_id = random.randrange(10000,65000)
    
    # Create ICMP Packet
    packet = ICMPPacket(icmp_id=pkt_id).raw

    # Send ICMP Packet
    while packet:
        sent = s.sendto(packet, (addr, 1))
        packet = packet[sent:]

    return pkt_id


def main():
    # create socket
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    
    # take Input
    addr = raw_input("[+] Enter Domain Name : ") or "www.google.com"
    
    # Request sent
    ID = single_ping_request(s, addr)

    # Catch Reply
    reply = catch_ping_reply(s, ID, time.time())

    if reply:
        print reply

    # close socket
    s.close()
    return

if __name__=='__main__':
    main()

Explanation



  • line 58, To make a raw socket



This Tutorial Ends Here,
I Hope You Enyed it

Code ICMP Raw Packet in Python

Namaste Friends,



In today's tutorial, I am going to tell you about how we can create or write Raw ICMP packet using python struct module.


Introduction

ICMP stands for Internet Control Message Protocol. Icmp protocol is used to provide an error reporting and query management protocol used by various types of Internet Devices like a router.
In simple words, ICMP protocols created to do connection checking, Connection status, Device availability Etc. For Example, With the help of ICMP packet, we can easily find the availability of an IP address into our Network.


How?


Well, To Find The Find the availability of any IP address Into our network. We simply Just need to send an ICMP packet with request codes, IP address and Source IP Address and if that Specific Device contains same IP address will available on our network, it will reply with another ICMP packet that will contain its information. So, With the help of this simple techniques, we can find the availability of any IP in our network but the only condition is, Client need to reply back with ICMP packet. Actually, Almost all device like to reply on ICMP packet but because of security feature, many devices don't reply back.


Format Of ICMP Packet






Requirement


  • Python 2.x Or 3.x
  • Struct Module
  • Pye Project (Only If you want to verify Packet On Wireshark)




Simplest Form Of codes To Make A ICMP Packet


 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class ICMPPacket:
    def __init__(self,
        icmp_type = ICMP_ECHO_REQUEST,
        icmp_code = 0,
        icmp_chks = 0,
        icmp_id   = 1,
        icmp_seq  = 1,
        data      ='' ,
        ):

        self.icmp_type = icmp_type
        self.icmp_code = icmp_code
        self.icmp_chks = icmp_chks
        self.icmp_id   = icmp_id
        self.icmp_seq  = icmp_seq
        self.data      = data
        self.raw = None
        self.create_icmp_field()

    def create_icmp_field(self):
        self.raw = struct.pack(ICMP_STRUCTURE_FMT,
            self.icmp_type,
            self.icmp_code,
            self.icmp_chks,
            self.icmp_id,
            self.icmp_seq,
            )

        # calculate checksum
        self.icmp_chks = self.chksum(self.raw+self.data)

        self.raw = struct.pack(ICMP_STRUCTURE_FMT,
            self.icmp_type,
            self.icmp_code,
            self.icmp_chks,
            self.icmp_id,
            self.icmp_seq,
            )

        return 

    def chksum(self, msg):
        s = 0       # Binary Sum

        # loop taking 2 characters at a time
        for i in range(0, len(msg), 2):

            a = ord(msg[i]) 
            b = ord(msg[i+1])
            s = s + (a+(b << 8))
            
        
        # One's Complement
        s = s + (s >> 16)
        s = ~s & 0xffff

        return s


Explanation



  • __init__ function to take inputs.
  • create_icmp_feild function to make an ICMP packet structure
  • check_sum function is to calculate packet checksum value






Another Simplest Form To Make ICMP Packet Extractor


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ICMP HEADER Extraction
def ext_icmp_header(data):
    icmph=struct.unpack(ICMP_STRUCTURE_FMT, data)
    data={
    'type'  :   icmph[0],
    "code"  :   icmph[1],
    "checksum": icmph[2],
    'id'    :   icmph[3],
    'seq'   :   icmph[4],
    }
    return data


Complete Codes  (Need Pye Project Scripts To Run it Correctly.



  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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
# import modules
import struct
import socket
from IP import LoadIP
from Ether import EtherPacket

# Header is type (8), code (8), checksum (16), id (16), sequence (16)
#    header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, 0, id, 1)
ICMP_STRUCTURE_FMT = 'bbHHh'
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.

ICMP_CODE = socket.getprotobyname('icmp')
ERROR_DESCR = {
    1: ' - Note that ICMP messages can only be '
       'sent from processes running as root.',
    10013: ' - Note that ICMP messages can only be sent by'
           ' users or processes with administrator rights.'
    }


class ICMPPacket:
    def __init__(self,
        icmp_type = ICMP_ECHO_REQUEST,
        icmp_code = 0,
        icmp_chks = 0,
        icmp_id   = 1,
        icmp_seq  = 1,
        data      ='' ,
        ):

        self.icmp_type = icmp_type
        self.icmp_code = icmp_code
        self.icmp_chks = icmp_chks
        self.icmp_id   = icmp_id
        self.icmp_seq  = icmp_seq
        self.data      = data
        self.raw = None
        self.create_icmp_field()

    def create_icmp_field(self):
        self.raw = struct.pack(ICMP_STRUCTURE_FMT,
            self.icmp_type,
            self.icmp_code,
            self.icmp_chks,
            self.icmp_id,
            self.icmp_seq,
            )

        # calculate checksum
        self.icmp_chks = self.chksum(self.raw+self.data)

        self.raw = struct.pack(ICMP_STRUCTURE_FMT,
            self.icmp_type,
            self.icmp_code,
            self.icmp_chks,
            self.icmp_id,
            self.icmp_seq,
            )

        return 

    def chksum(self, msg):
        s = 0       # Binary Sum

        # loop taking 2 characters at a time
        for i in range(0, len(msg), 2):

            a = ord(msg[i]) 
            b = ord(msg[i+1])
            s = s + (a+(b << 8))
            
        
        # One's Complement
        s = s + (s >> 16)
        s = ~s & 0xffff

        return s


# ICMP HEADER Extraction
def ext_icmp_header(data):
    icmph=struct.unpack(ICMP_STRUCTURE_FMT, data)
    data={
    'type'  :   icmph[0],
    "code"  :   icmph[1],
    "checksum": icmph[2],
    'id'    :   icmph[3],
    'seq'   :   icmph[4],
    }
    return data

def main():
    icmp = ICMPPacket()
    print ext_icmp_header(icmp.raw)
    ip = LoadIP(tcp=icmp, ip_proto=socket.IPPROTO_ICMP)
    eth = EtherPacket(data=ip)

    
    try:
        from samples.wsk import ShowPacket
        pkt = eth.raw +ip.raw+icmp.raw
        ShowPacket([pkt], link_type=1)
    except Exception as e:
        print e
        print "[+] Unable To Find pye.samples.wsk script."
    return


if __name__=='__main__':
    main()



I hope you enjoy this tutorial.

Keep Reading and
have a nice day.

how to get mac address using python socket

Namaste Friends,



Introduction


In this post, I am going to tell you about how we can easily get the address of our interface using python socket module. Actually, To retrieve the mac address of our card here we going to use python socket module sock name function.

Sock name function returns socket information as a tuple. so, to get the mac address of your interface card, first, we need to create a dummy socket object and then, bind it with the specific interface. basically, specific interface means the interface whose address you want to find.

Example Code


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import socket
from binascii import hexlify

# get mac address
def get_mac(interface, p=0):

    # create dummy socket
    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)

    # bind it with interface name
    s.bind((interface,p))

    # extract mac address
    mac =  hexlify(s.getsockname()[4])

    # close socket
    s.close()

    #return value
    return mac

Explanation


  • line 8, To create a dummy socket object.
  • line 11, Bind socket with interface card.
  • line 14, extract mac address from tuple
  • line 17, close socket