본문 바로가기

# 프로그래밍 개발/02. Python

How to get client's IP address using Cherrypy

반응형

# Cherrypy 에서 Client의 IP address를 얻는 방법 

최근 프로젝트 과정 중에 Cherrypy를 이용해서 서버를 만들었습니다.

그러던 중 접속한 클라이언트의 IP 주소를 기록해야될 필요성이 생겨서 찾아보았는데 많은 정보가 없었기 때문에 기록을 하고자 합니다. 

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
import cherrypy
 
 
class MyWebService(object):
    @cherrypy.expose
    @cherrypy.tools.json_out()
    @cherrypy.tools.json_in()
    def getResult(self, query):
        return sendResult2ggsheet(query)
 
    @cherrypy.expose
    def index(self):
        return open("mainIndex.html")
 
def sendResult2ggsheet(query):
    
    try:
        clientIP = cherrypy.request.headers.get('Remote-Addr')
        print(type(clientIP))
        print(clientIP) # 192.0.0.1
 
    except Exception as e:
        print("error" + e)
    
    return 0
 
if __name__ == '__main__':
 
    config = {'server.socket_host''***.***.***.***',
              'server.socket_port'80,              
              'tools.response_headers.on'True,
              'tools.response_headers.headers': [('Access-Control-Allow-Origin''*')],
              }
    CP_CONF = {
        '/': {
            'tools.staticdir.on'True,
            'tools.staticdir.dir': abspath('./'
        }
    }
 
    cherrypy.config.update(config)
 
    cherrypy.quickstart(cherrypy.Application(MyWebService()), '/', CP_CONF)
cs

cherrypy.reqeust.headers의 데이터를 분석하면, json 형태로 접속한 클라이언트의 정보를 얻을 수 있습니다.

그 중 'Remote-Addr' tag의 값이 접속한 클라이언트의 ip 주소입니다. 

반응형