전기전자공학/프로젝트

[컴퓨터망] UDP ping 프로젝트

LinZBe4hia 2018. 3. 25. 02:50

컴퓨터망 수업에서 교수님께서 python으로 UDP ping을 구현하는 미니(?) 프로젝트를 과제로 내어주셨다!


간단하게 UDP를 설명하자면,

이 UDP는 전송 계층에 있는 프로토콜로 비연결형 서비스를 제공한다.

데이터를 주고받는 데에 쓰이는데 왜 비연결형이라고 하는걸까??

그 이유는 UDP는 송신자와 수신자 사이 정확히 연결이 됐는지 확인하지 않고 바로 데이터를 보내기 때문이다!

사실 이 프로토콜은 그냥 데이터 전송에만 포커스를 맞춘 프로토콜이라 데이터 전송에 신경쓰는 게 별로 없다.

보안이던가 네트워크 트래픽을 고려하지도 않는다. 그치만 여기서 장점이 있다!

보내는 것에만 신경쓰기 때문에 속도가 빠르다! 그래서 비디오나 오디오, 즉 텍스트보다 용량이 큰 데이터들을 보내는 데 자주 쓰인다


이제 본격적으로 과제를 풀어보자!


과제의 목표는 크게 3가지

1. 데이터 전송에 대한 이해

2. 적당한 소켓의 timeout 시간

3. Ping 이해 & 활용


내가 해야 할 것

1. 과제 읽기 - 요구 조건 파악

2. 보고서 작성 ㅠ..


1. 요구 조건 파악
 - python으로 Server - Client 구조로 UDP 소켓 프로그래밍 이해
 - Server Code 해석
 - Client Code 작성 
     > 10 pings
     > ping reply 기다리는 시간 1초 설정
     > 메세지 형태: ping [메세지 번호] [RTT]


Server Code

#-*-coding:utf-8-*-import random                # Generate randomized lost packets
from socket import *

# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('127.0.0.1', 12000))

while True:
    # Generate random number in the range of 0 to 10
        rand = random.randint(0, 10)
    # Receive the client packet along with the address it is coming from
        message, address = serverSocket.recvfrom(1024)
    # Capitalize the message from the client
        message = message.upper()
        #print message

# If rand is less is than 4, we consider the packet lost and do not respond
        if rand < 4:
                continue
    # Otherwise, the server responds
        serverSocket.sendto(message, address)





Packet Loss


앞에도 말했듯이 UDP는 데이터가 잘 전해지는 지 아닌지 신경쓰지 않는 '비신뢰적인' 전송 서비스를 제공하므로, 

전달되어야 하는 메세지가 도중에 수신자에게 도착하지 않을 수 있다. 

사실 요즘은 패킷을 잃어버리는 경우는 흔치 않다. 그렇지만, 여기선 인위적으로 패킷을 잃도록 설정해준다. 

그리곤 얼마나 잃어버렸는지 확인해본다! 위의 서버 코드에서 랜덤한 숫자를 생성하고는 특정 패킷을 잃어버렸는지 아닌지를 체크하면 된다!

* The server creates a variable randomized integer which determines whether a particular incoming packet is lost or not.



Client Code


자! 클라이언트 코드를 작성할 때가 왔당!

#-*-coding:utf-8-*-
import socket #error with from socket import* Importing the libraries that I needed separately fixed the issue
from socket import AF_INET, SOCK_DGRAM
import time

print "Running" #Statement to let me know the program started correctly
print "==============================="
serverName = "127.0.0.1" #server set as general computer ip
clientSocket = socket.socket(AF_INET,SOCK_DGRAM) #create the socket
clientSocket.settimeout(1) #sets the timeout at 1 second
sequence_number = 1 #variable to keep track of the sequence number
while sequence_number<=10:
        message = "Ping" #message to be sent
        start=time.time() #assigns the current time to a variable
        clientSocket.sendto(message,(serverName, 12000))#sends a message to the server on port 8000

        try:
                message, address = clientSocket.recvfrom(1024) #recieves message from server
                elapsed = (time.time()-start) # calculates how much time has elapsed since the start time
                elapsed = float("{0:.5f}".format(elapsed))
                print message + "    " + str(sequence_number) +  "    RTT: " + str(elapsed) + " sec" #issue with printing elapsed unless it was changed to a string

        except socket.timeout: #if the socket takes longer that 1 second, it does the following instead of the try
                print sequence_number
                print "Request timed out"

        print ""
        sequence_number+=1 #sequence number is increased after all of the other statements in the while

        if sequence_number > 10: #closes the socket after 10 packets

                clientSocket.close()



UDP prgramming Result