[컴][파이썬] python 에서 간단한 socket programming

python socket programming / http request with different ip address




자세한 설명은 ref. 1 을 참고하자.

여기서는 간단하게 TCP packet 을 만들고, 그 위에 Http message 를 얹은 source code 를 확인하자.



#-*- coding: utf-8 -*-


__author__ = 'namhadmin'


import httplib2

import socket
import sys

import re
import time


class QueryClient:
    def __init__(self):

        self.socket = None

    def _createSocket(self):
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # IPv4 and TCP
        except socket.error, msg:
            print 'Failed to create socket. Error code : ' + str(msg[0]) + ', Error message : ' + msg[1]
            sys.exit()

    def _connectAndSend(self, remote_ip, port, message):
        self.socket.connect((remote_ip, port))
        self.socket.setblocking(1)
        try:
            self.socket.sendall(message)

        except socket.error:
            # send failed
            print
            'Send failed'
            sys.exit()
        print
        'Send successfully'

    def _printResult(self, data, remote_ip):
        plm = re.compile(r'Last-Modified:\s*(.*?)\r\n', re.DOTALL)
        pd = re.compile(r'Date:\s*(.*?)\r\n', re.DOTALL)
        matchLastMod = plm.search(data);
        matchDate = pd.search(data);
        if matchLastMod is not None:
            last_mod_time = matchLastMod.group(1)
            date = matchDate.group(1)
            difSecFromDate = time.mktime(time.strptime(date, "%a, %d %b %Y %H:%M:%S GMT")) - time.mktime(
                time.strptime(last_mod_time, "%a, %d %b %Y %H:%M:%S GMT"))
            difSecFromCurrent = time.mktime(time.gmtime()) - time.mktime(
                time.strptime(last_mod_time, "%a, %d %b %Y %H:%M:%S GMT"))

            okDifSecFromDate = 'ok' if difSecFromDate <= 600 else 'nok'
            okDifSecFromCurrent = 'ok' if difSecFromCurrent <= 600 else 'nok'

            print 'ip address = ', remote_ip
            print 'current time - last_modified = %s (%s)' % (difSecFromCurrent, okDifSecFromCurrent)
            print 'date - last_modified = %s (%s)' % (difSecFromDate, okDifSecFromDate)



    def run(self):



        # try:
        #     remote_ip = socket.gethostbyname(host)
        # except socket.gaierror:
        #     print 'Hostname could not be resolved. Exiting'
        #     sys.exit()
        #
        # print 'Ip address of ' + host + ' is ' + remote_ip




        host = "image.cjmall.com"
        port = 80
        message = 'GET /cjupload/mcom_web/xml/app/oclock/ctg/OclockItem_291295.json HTTP/1.1\r\n\
Host: ' + host + '\r\n\
Connection: keep-alive\r\n\
Cache-Control: no-cache\r\n\
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n\
Pragma: no-cache\r\n\
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36\r\n\
Accept-Encoding: gzip,deflate,sdch\r\n\
Accept-Language: ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4\r\n\
\r\n'


        remote_ip = '211.110.198.68'
        self._createSocket()
        self._connectAndSend(remote_ip, port, message)
        data = self.socket.recv(4096)
        self._printResult(data, remote_ip)
        self.socket.close()

        remote_ip = '211.110.198.73'
        self._createSocket()
        self._connectAndSend(remote_ip, port, message)
        data = self.socket.recv(4096)
        self._printResult(data, remote_ip)
        self.socket.close()





if __name__ == "__main__":

    client = QueryClient()
    client.run()



References

  1. http://www.binarytides.com/python-socket-programming-tutorial/

댓글 없음:

댓글 쓰기