본문 바로가기

python/python 응용

Python 소켓을 이용해 구글 웹서버에 접속해보았음

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 

 

 

이글은 제가 공부하고 느낀것을 정리한글이라 틀릴수도있습니다


기본적인것부터 정리해보자


가장먼저 소켓을 생성해보자


1
2
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cs


이런식으로 소켓을 생성할수가있다


두개의 인자에서


AF_INET는 ipv4로 통신하겠다는거고


만약 ipv6로 하려면 AF_INET 대신에 AF_INET64로 값을 적어주면된다.

 

SOCK_STREAM 은 연결형(TCP)으로 통신하겠다는거 같다.


만약 연결형(TCP)말고 비연결형(UDP)로 통신하려면 SOCK_DGRAM값을 적어주면되는거같다.


여기까지는 소켓을 생성하는 가장 기본적인 단계이다.


저렇게 두줄을 딸랑적으면 소켓이 생성됬는지 안됬는지 모르기떄문에


코드를 추가해서 재대로 생성이되었는지확인해보자.


참고로 필자는 python 3.5.1 에서 코딩한다


1
2
3
4
5
6
7
import socket
 
try:
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket successfully created")
except socket.error as err:
    print("socket creation failed with error %s ") %(err)
cs


이런식으로 짤수가있다


먼저 소켓이 재대로 생성이되었다면 Socket successfully created 라고 문구를 띄우게 만들었다


만약에 소켓이 재대로 생성되지않아 에러가 발생햇다면


err값에 그 이유를 넣고


socket creation failed with error  ~ 에러이유 가 뜨게 만들어보았다.


파이썬은 참편리한거같다.


목표는 구글 웹서버에 접속하는거니 좀더 나아가보자


일단 구글이 살아있는지 죽었는지 ping 으로 확인해보자



잘간다.


이제 구글의 ip를 가져와볼것이다


사실 cmd에서 ping을치면 구글의 google.co.kr의 아이피주소가 나와서


ip 변수에 저대로 입력하면되지만


socket 클래스를 활용해보았다


socket.gethostbyhost()을 이용하면 해당하는주소의 ip를 가져올수있다.


1
2
3
4
5
import socket 
 
ip = socket.gethostbyname('www.google.com')
print ip
 
cs



이런식으로 구글의 ip주소를 가져와서 ip라는 변수에 값을넣고 ip를 출력하는 코드를 작성할수가있다


만약 ip = socket.gethostbyname('www.google.com')


이런식으로 한줄만 서버주소가 잘못되거나 다른문제로인해 값을 받아오지못하면 난감하니


이부분도 위처럼 만들어보았다.


1
2
3
4
5
6
try:
    ip=socket.gethostbyname('google.co.kr')
    port=80
except socket.gaierror:
    print("error yo")
    sys.exit()
 
cs


잘받아왔다면 연결을위해 port변수에 포트번호를 적어주었고


만약에 받아오지못하고 에러가 뜨면 에러가 떳다고 알려주고 프로그램을 종료하게 짜봣다.


현재까지 코드를 정리해보면


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import socket
import sys
try:
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket successfully created")
except socket.error as err:
    print("socket creation failed with error %s ") %(err)
 
try:
    ip=socket.gethostbyname('google.co.kr')
    port=80
except socket.gaierror:
    print("error yo")
    sys.exit()
 
cs


이런식으로 짤수가잇다


이제 모든 준비가 끝낫으니 connect 를 해보자


연결은 이렇게 해주면 되는거 같다

1
s.connect((ip.port))
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import socket
import sys
try:
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket successfully created")
except socket.error as err:
    print("socket creation failed with error %s ") %(err)
 
try:
    ip=socket.gethostbyname('google.co.kr')
    port=80;
except socket.gaierror:
    print("error yo")
    sys.exit()
 
s.connect((ip,port))
 
print("연결성공")
cs


처음으로 파이썬으로 소켓을 다루어보았다.


조금만 바꾸면 nmap처럼 포트스캔도 가능할거같다


영어문서를 보고 공부한거라


틀린것이 있다면 지적해주세요