Monday, August 12, 2013

Perl Socket-Programming by using UDP protocol.


 Perl 의 Socket 이라는 Module 을 이용한 Socket Programming.
먼저 Server side Programming.

우선 Basic statement

#Server side:
#! /usr/bin/perl -w

use strict;
use Socket;   #Socket Module 사용

#사용할 Port 와 최대로 받고 싶은 길이, 도메인 네임을
#use constant 를 이용하여 정의. (C에서 #define 과 같은 의미로 보면된다)

use constant SIMPLE_UDP_PORT => 4001;
use constant MAX_RECV_LEN => 1500;
use constant LOCAL_INETNAME => 'localhost';


#다음 Socket Module 의 함수를 이용하여 스칼로로 리턴

#- 간단한 함수의 정의
#getprotobyname() : protocol name 으로 service port number 를 리턴.
#gethostbyname() : domain name 으로 host IP 를 리턴.
#sockaddr_in(): 포트정보와 IP Address 정보로 socket address 를 리턴
#혹은 socket address 로 IP Address 와 포트정보를 리턴.

my $trans_serv = getprotobyname( 'udp' );
my $local_host = gethostbyname( LOCAL_INETNAME );
my $local_port = SIMPLE_UDP_PORT;
my $local_addr = sockaddr_in( $local_port, INADDR_ANY );

#socket() : socket open 상수전달
#(Protocol family, Address family, Socket Type, Linux specific shortcut)

socket( UDP_SOCK, PF_INET, SOCK_DGRAM, $trans_serv )
     or die "udp_s2: socket creation failed : $!\n";

bind( UDP_SOCK, $local_addr )
     or die "udp_s2: bind to address failed : $!\n";


#Client 로 부터 전달 받은 메시지를 while문을 통해 출력.

my $data;
while( 1 ){
     my $from_who = recv( UDP_SOCK, $data, MAX_RECV_LEN, 0 );
     if ( $from_who ){
          my ( $the_port, $the_ip ) = sockaddr_in( $from_who );
          my $remote_name = gethostbyaddr( $the_ip, AF_INET );
          warn "Received from $remote_name: $data\n";
     }
     else{
          warn "Problem with recv: $!\n";
     }
}


#Client side:

#! /usr/bin/perl -w

use strict;
use Socket;
use constant SIMPLE_UDP_PORT => 4001;
use constant REMOTE_HOST => 'localhost';

#||(or) : 명령행 전달인자가 있을경우 취하고 없으면 REMOTE_HOST 상수를 이용해 받음.
#protocol name 으로 서비스 포트넘버를  리턴.
#or 의 기본 연산원리를 이용한 것으로 첫번째 인자가 false 일 경우 두번째 인자를
#검사를 하지만, 첫번째 인자가 True 인경우 두번째 인자와는 관계없이 True 이므로
#두번째 인자는 검사하지 않는다. 즉 아규먼트가 있으면  shift 되지만 없을경우
#위에서 정의된 REMOTE_HOST 상수값이 리턴된다.

my $remote = shift || REMOTE_HOST;
my $trans_serv = getprotobyname( 'udp' );
my $remote_host = gethostbyname( $remote )
or die "udp_c2: name lookup failed : $remote\n";

my $remote_port = shift || SIMPLE_UDP_PORT;
my $destination = sockaddr_in( $remote_port, $remote_host );

socket( UDP_SOCK, PF_INET, SOCK_DGRAM, $trans_serv )
or die "udp_s2: socket creation failed : $!\n";

#send(): $destination 측으로 $data 를 메시지로 전송.

my $data = "Hello Server ~~!!";
send( UDP_SOCK, $data, 0, $destination )
or warn "udp_c2: send to socket failed.\n";

close UDP_SOCK
or die "udp_c2: close socket failed : $!\n";


#Referenced 'Programming the network with perl'    - Paul Barry -








No comments:

Post a Comment