global_ip()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 2
Metric Value
cc 3
c 3
b 1
f 2
dl 0
loc 17
rs 9.4285
1
import socket
2
import requests
3
import re
4
import platform
5
import subprocess as sub
6
ip_pattern=r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}"
7
api_1="http://ipinfo.io/ip"
8
9
def local_ip(DEBUG=False):
10
    '''
11
    return local ip of computer in windows by socket module and in unix with hostname command in shell
12
    :param DEBUG: Flag for debug mode
13
    :type DEBUG : bool
14
    :return: local ip as string
15
    '''
16
    try:
17
        ip=socket.gethostbyname(socket.gethostname())
18
        if ip!="127.0.0.1":
19
            return ip
20
        elif platform.system()!="Windows":
21
            command=sub.Popen(["hostname","-I"],stdout=sub.PIPE,stderr=sub.PIPE,stdin=sub.PIPE,shell=False)
22
            response=list(command.communicate())
23
            if len(response[0])>0:
24
                return str(response[0])[2:-4]
25
            else:
26
                return "Error"
27
        else:
28
            return "Error"
29
30
    except Exception as e:
31
        if DEBUG==True:
32
            print(str(e))
33
        return "Error"
34
35
def global_ip(DEBUG=False):
36
    '''
37
    return ip with by http://ipinfo.io/ip api
38
    :param DEBUG:Flag for debug mode
39
    :type DEBUG:bool
40
    :return: global ip as string
41
    '''
42
    try:
43
        new_session=requests.session()
44
        response=new_session.get(api_1)
45
        ip_list=re.findall(ip_pattern,response.text)
46
        new_session.close()
47
        return ip_list[0]
48
    except Exception as e:
49
        if DEBUG==True:
50
            print(str(e))
51
        return "Error"
52
53