Programming/C#2011. 10. 19. 02:01
.. too boring that's why I made this.

Actually, there are a lot of easier ways than the way that I did
I only use one library method, which is Math.pow

Here is the source code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Practice
{
    public class Point
    {
        public static void Main()
        {
            for (int i = 0; i < 30000; i++)
            {
                if (Palindromic(i))
                    Console.WriteLine(i);
            }
        }

       public static bool Palindromic(int n)
       {
           // get how many digit we have
           //
           //int temp = n;
           int i;
           int temp;
           int digit = 0;
           for(temp = n;temp>0;digit++)  // get the number of digits.
           {
               temp /= 10;   
           }


           int firstDigit = 0;
           int secondDigit = 0;

           for(i=0;i<(digit/2);i++)
           {
               firstDigit = (n / (int)Math.Pow(10,i)) % 10;
               secondDigit = (n / (int)Math.Pow(10,digit-(i+1))) % 10;
               if(firstDigit != secondDigit)
                   break;
           }
           if (i == (digit / 2))
               return true;
           return false;
           
       }
           
    }
}

'Programming > C#' 카테고리의 다른 글

How to shutdown a computer in c#  (0) 2011.12.25
Posted by 박세범
Programming2011. 10. 15. 03:04
you do not have to use thread,

However, if you want to use "Double-buffering" mechanism. at least you should know how to use Thread.
This code is really messed up though Sorry =)


package com.Circle;

import android.app.Activity;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.content.*;

public class CircleActivity extends Activity {
    /** Called when the activity is first created. */

    MyView vw;                    // Circle을 만들기 위한 객체 선언
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vw = new MyView(this);    // 객체 할당
        setContentView(vw);        // 이 객체를 보여주도록 한다.
       
    }
    public class MyView extends View{    // view클레스를 상속하는 MyView class
        int num = 0;                // 이 변수는 0부터 360까지 증가되는 변수이다
        Paint pnt = new Paint();    // paint 변수 선언
        RectF rf = new RectF(50,50,150,150);    // 타원을 넣기 위한 RectF 클레스 선언
        Thread th = new Thread(new ThreadForCircle());    // 실시간 작동을 위하여 thread를 생성하였다.
                                                // ThreadForCircle은 Runnable interface를 가진다.
        int color;                    // color를 저장하기 위한 변수 선언
       
       
        public MyView(Context context){
            super(context);        //생성자 부분
            color = Color.argb(0xFF, (int)(Math.random()*256), (int)(Math.random()*256), (int)(Math.random()*256));
            // 랜덤한 색깔 생성
            pnt.setAntiAlias(true);    // AntiAlias모드를 on, 더욱 자연스럽다.
            th.start();                // thread를 시작한다.
        }
       
        public void onDraw(Canvas canvas){    // 실질적으로 원을 그리는 함수
            if(num > 360){            // 만약 원하나가 이미 그려졌다면
                color = Color.argb(0xFF, (int)(Math.random()*256), (int)(Math.random()*256), (int)(Math.random()*256));
                // 색깔을 바꾸고
                num=0;
                // 처음부터 다시 그릴 준비를 한하.
            }
            else{
                pnt.setColor(color);    // paint 객체에 색깔을 지정한후
                canvas.drawArc(rf, 0, num, true, pnt);    // 부채꼴을 그린다. num값은 thread에 의해 바뀌며,
                                                        // thread는 onDraw를 호출하게 된다.
                Toast.makeText(CircleActivity.this, new String("hello"), Toast.LENGTH_SHORT).show();
            }
        }
        public int getNum(){            // 부채꼴의 현재 크기를 얻기 위한 함수
            return num;           
        }
       
        public void setNum(int _num){    // 부채꼴의 크기를 변경할 함수
            num = _num;
        }
    }


    public class ThreadForCircle implements Runnable{    // Runnable interface를 가지며
        int returnValue;                                // 변경될 크기가 저장될 변수
        public void run(){                                // thread생성 후에 무조건 run이 실행된다.
            while(true){                                // 반복문을 계속 돌린다.
                try {                                    // sleep을 위한 예외처리
                    Thread.sleep(50);                    // 50/1,000초 쉰다.
                    returnValue = vw.getNum() + 6;        // 6도씩 부채꼴이 증가하게 된ㄷ.
                    vw.setNum(returnValue);                // 이 값을 view의 객체에 넣어준다.
                    vw.postInvalidate();                // invalidate가 아닌데 그 이유는
                                                        // 현재 thread는 onDraw 함수가 없다.
                                                        // thread를 호출한 곳에서 invalidate하게 한다.
                } catch (InterruptedException e) {        // 예외 선언
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }         
            }
        }
    }
   
}

'Programming' 카테고리의 다른 글

Spring3.0 ajax를 이용한 json 주고밖기(@RequestBody)  (0) 2012.11.18
Open SSH Server  (0) 2012.10.08
File copy by using windows API  (0) 2011.08.31
Win32 API tutorial  (0) 2011.08.26
Posted by 박세범

See struct stat and fstat;

pretty simple example, and getMode show a good example in terms of bit operation.



#include <stdio.h>              // 표준입출력헤더파일

   #include <stdlib.h>            

   #include <sys/stat.h>           // stat 구조체가선언되어있는헤더파일

   #include <sys/types.h>          // perror 함수호출을위한헤더파일

   #include <unistd.h>

   #include <fcntl.h>              // file control flag가저장되어있는헤더파일

 

   #define MAX_BUF 64              // BUF 크기를정의한다.

 

  char* getMode(mode_t mode,char* bit);   // getMode 함수는현재파일의속성을출력한다.

 

  int main(int argc, char *argv[])        // 메인함수시작

  {

      int fdForRead;                     // file descriptor for read

      int fdForWrite;                    // file descriptor for write

      char buf[MAX_BUF];                 // to define buffer

      int read_size;                     // readoff셋으로활용되는변수

      int write_size;                           // wrtieoff셋으로활용될변수

      struct stat info;                  // 파일의정보를받을구조체

      int fs;                                   // fstat의리턴값을저장할변수

      int modeInfo;                      // getModemode를받을정수

      char bit[10];                             // rwxrwxrwx로출력하기위한변수

      int i=0;                           // for문의counter 변수

 

      if(argc != 3)                      // 만약arument의사용법이잘못됐다면

      {

          printf("Usage : mycp.out source_file_name destination_file_name\n\n");

                                         // 사용법을알려준후

          exit(-1);                      // 프로그램을종료한다.

      }

 

      fdForRead = open(argv[1], O_RDWR);   // 2번째argument를이용해서파일을열며읽기쓰기가능>

      if(fdForRead <0){                                // 만약읽기가실패한다면

          perror("cannot open the file because : ");  // 메세지를출력후

          exit(-1);                                    // 프로그램을종료한다.

     }

 

     printf("\n\nThis program is coping a file with the mode of file \n");

                                                         // 프로그램실행전출력메세지

 

     fstat(fdForRead, &info);    //fstat      수는file descriptor를이용하여stat 구조체에

                                 // file에대한정보를저장하며여기서우리는mode를얻을수있다.

 

     getMode(info.st_mode,bit);          // getMode는가져온mode정보를rwxrwxrwx 형태로bit에대입한다.

     printf("The mode = %s \n\n",bit);     // 현재파일의모드를출력하고

 

 

/*************************************************************************************

//                         Redirection

 

     // close(STDOUT_FILENO);    // 만약redirection을쓰고싶으면이주석을해제하면된다.

 

 ************************************************************************************/

 

 

     fdForWrite = open(argv[2], O_RDWR | O_CREAT | O_EXCL, info.st_mode);

                                           // stat 구조체에저장된st_mode를이용하여파일을생성하며

                                           // 만약파일명이중복된다면O_EXCL flag로인하여파일이생성되지않>

     if(fdForWrite == -1){                 // 파일생성에실패하거나파일이존재한다면

         perror("cannot open the file because :  ");     // 메세지와errno의메세지를같이출력한후

         exit(-1);                           // 프로그램을종료한다.

     }

      while(1){                                     // while문은파일이다써질때까지반복되며

          read_size = read(fdForRead, buf, MAX_BUF);  // 64바이트씩파일을읽는다

          if(read_size == 0)                       // 만약파일의끝이라면

              break;                               // 반복문을빠져나간다.

          write_size = write(fdForWrite, buf, read_size);     // 64바이트씩새로운file에쓴다.

 

         /******************** Redirection ******************************

                    

          //write_size = write(STDOUT_FILENO, buf, read_size);    // redirection을이용한file 출력

 

         ***************************************************************/    

 }

      printf("Successful!\n");     // 파일복사가완료되면메세지를생성후

      close(fdForRead);             // file descriptor들을닫아준다.

      close(fdForWrite);

      return 0;

  }

 

   char* getMode(mode_t mode,char* bit)       // file mode를출력하는함수

  {

      int i=0;                            // 반복문의counter

      int index=0;                        // index는문자를저장할떄쓰인다

      int modeInfo = 00777 & (unsigned long)mode;     // 777modeAND 연산한후

      for(i=256;i>0;i=i/2){                     // 그내용들을출력하는반복문을실행한다.

          if((modeInfo & i) == i)        // 만약i2^8부터2^0까지바뀌게되며

          {                              // and 연산이i값과같다면그flagset이다.

              if(index%3 == 0)                  // rwx 위치에맞게문자열에저장된다.

                  bit[index] = 'r';

              else if(index%3 == 1)

                  bit[index] = 'w';

              else

                  bit[index] = 'x';

          }

          else

              bit[index] = '-';          // 만약flag0이라면'-'로문자열을채운다.

          index++;                       // index를증가시킨후

      }

      return bit;                     // 받았던문자열을반환한다.

}


'Programming > System programming' 카테고리의 다른 글

dup2() and pipe() system call for pipe fuction in shell  (1) 2011.11.03
sys/types.h  (2) 2011.10.10
Posted by 박세범
please take a look at accept() method,
second and third parameters must have values
don't forget

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    struct sockaddr_in local;
    struct sockaddr_in client;
    int *csize;
    int s;    int s1;    int rc; char buf[1];
    local.sin_family = AF_INET;
    local.sin_port = htons(5300);
    local.sin_addr.s_addr = htonl(INADDR_ANY);
   
    char getTime[255];

    //added by Justin
   
    printf("A server has been started, the port number is reserved as 5300\n\n");


    s = socket(PF_INET, SOCK_STREAM, 0);
    if(s<0){
        perror("socket call failed");
        exit(1);
    }

    rc = bind(s, (struct sockaddr *)&local, sizeof(local));
    if(rc<0){
        perror("bind call failure");
        exit(1);
    }


    printf("A server is waintg for a client request\n\n");

    rc = listen(s,5);
    if(rc){
        perror("listen call failed");
        exit(1);
    }



    csize = sizeof(client);        // this is used to get a ip address using accept()

    s1= accept(s,(struct sockaddr*)&client ,&csize);    // we need to know the ip address of a client
    // to get client address. then we have to send this client
    // address to the client.

    printf("Conntection established!\n\n");

    if(s1<0){
        perror("accept call failed");
        exit(1);
    }

    rc = recv(s1,getTime ,sizeof(getTime), 0);    // rc return the size of the data

    if(rc<=0){
        perror("recv call failed");
        exit(1);
    }

    printf("\nCurrent time from client : %s \n", getTime);        //print current Time

    printf("\n\nA server will send a client's IP address \n");

    rc = send(s1, &client , sizeof(client), 0);        // send a structure of sockaddr_in to the client
    if(rc <= 0)                        // if it failes
    {
        perror("send call failed");
        exit(0);
    }
}





'Programming > Network Programming' 카테고리의 다른 글

TCP programming basis  (0) 2011.10.28
.. no regret..  (0) 2011.10.26
get client IPadrress in server side  (0) 2011.10.10
Reference for unix socket api  (0) 2011.09.29
TCP/IP  (0) 2011.09.21
Posted by 박세범
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    struct sockaddr_in local;
    struct sockaddr_in client;
    int *csize;
    int s;    int s1;    int rc; char buf[1];
    local.sin_family = AF_INET;
    local.sin_port = htons(5300);
    local.sin_addr.s_addr = htonl(INADDR_ANY);
   
    char getTime[255];

    //added by Justin
   
    printf("A server has been started, the port number is reserved as 5300\n\n");


    s = socket(PF_INET, SOCK_STREAM, 0);
    if(s<0){
        perror("socket call failed");
        exit(1);
    }

    rc = bind(s, (struct sockaddr *)&local, sizeof(local));
    if(rc<0){
        perror("bind call failure");
        exit(1);
    }


    printf("A server is waintg for a client request\n\n");

    rc = listen(s,5);
    if(rc){
        perror("listen call failed");
        exit(1);
    }



    csize = sizeof(client);        // this is used to get a ip address using accept()

    s1= accept(s,(struct sockaddr*)&client ,&csize);    // we need to know the ip address of a client
    // to get client address. then we have to send this client
    // address to the client.

    printf("Conntection established!\n\n");

    if(s1<0){
        perror("accept call failed");
        exit(1);
    }

    rc = recv(s1,getTime ,sizeof(getTime), 0);    // rc return the size of the data

    if(rc<=0){
        perror("recv call failed");
        exit(1);
    }

    printf("\nCurrent time from client : %s \n", getTime);        //print current Time

    printf("\n\nA server will send a client's IP address \n");

    rc = send(s1, &client , sizeof(client), 0);        // send a structure of sockaddr_in to the client
    if(rc <= 0)                        // if it failes
    {
        perror("send call failed");
        exit(0);
    }
}


accept should have the sockaddr struct as long as we want to know about client's address information
In this example, client.sin_addr has a IP address of a client and client.sin_port has a port #


'Programming > Network Programming' 카테고리의 다른 글

.. no regret..  (0) 2011.10.26
The example of one server that sends a client ID  (0) 2011.10.15
Reference for unix socket api  (0) 2011.09.29
TCP/IP  (0) 2011.09.21
The concept of TCP/IP part 1.  (2) 2011.09.07
Posted by 박세범

in order to get the mode of a file, we need to get the information of Inode struct

fortunately, there is a api stat() or fstat()

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int main(int argc, char *argv[])
{
       int fd;
       struct stat info;                  // in order to get the status of a file
       fd = open(argv[1],O_REWR);
       fstat(fd, &info);                   //fstat(int fileDescriptor, struct stat* info)
       printf(fd, (unsigned long)info.st_mode);
        return 0;
}

st_mode is one structure in struct stat info. it has a mode of a file(permission)
so if we use this we can copy a file whose mode is exactly same as the file we want to copy from

Posted by 박세범


Prototype

Return value

Parameter

The role of function

int socket(int domain,
int type int protocol)

양의 정수 : socket descriptor
-1 :
소켓 생성 실패

domain : PF_INET: protocol type
                 PF_INET6 : IPv6
                  PF_UNIX : UNIX
방식의 프로토콜
type : SOCK_STREAM : TCP
           SOCK_DGRAM : UDP

           SOCK_RAW : raw(ICMP)
protocol : IPPORTO_TCP
                  IPPROTO_UDP
                  0(for TCP, UDP)

새로운 소켓을 만들 쓰이며, 반드시 return 값을 가지고 있어야 한다. Return 값은 추후 소켓을 구별 하는대 쓰인다.

함수는 bind() or connect() 함께 쓰인다.

int close(int socket)

0 : 소켓 종료가 정상적으로 이뤄짐
-1 :
소켓 종료를 실패함

socket : socket()에서 만들어진
               socket desrtiptor

소켓을 종료할 쓰이며, 상당시간 동안
time_wait
상태를 유지함에 유의하자.

int bind(int socket,
const struct sockaddr *localaddr
int addrlen)

0 : bind 성공했을 경우
-1 : bind
실패했을 경우

socket : socket() return
localaddr :
서버의 주소를 가진 구조체, 대게 sockaddr_in
addrlen :
구조체의 크기

서버 프로그램이
sock
에게 port(이름) 할당(등록) 한다.

int listen(int socket, int queuesize)

0 : 성공했을 경우
-1 :
실패 했을 경우

socket : socket() 의핸 return socket descriptor
queuesize : queue
최대크기
                    
최대는 5이다

생성된 소켓이 client 연결을 기다리는 함수
queue
최대 길이를 설정한다.

int accept(int socket,
struct sockaddr *caddress
int *caddresslen)

-1 : 실패했을 경우
양의정수 : socket I/O 위한
non-negative descriptor
반환

socket :  socket() return
caddress : sockaddress_in
구조체 포인터,
                   client address
저장된다.
caddresslen : sockaddress_in
구조체의 길이의 포인터

Queue 들어있는 처음 연결을 추출하는 함수, 만약 queue 비어있다면 blocking 된다.
client
로부터 연결요청을 받아 통신을 위한
새로운 소켓을 생성한 연결한다.

int connect(int socket,
const struct sockaddr *serveraddress
int serveraddresslen)

0 : 성공했을 경우
0
아닌 정수값 : 실패할 경우

Socket : socket() return
serveraddress :
서버주소를 가지고 있는
                           
구조체의 포인터
serveraddresslen :
서버주소를 가지고 있는
                                 
구조체의 길이

Socket 다른 socket 연결한다.
서버와의 통신을 위해 통신 연결을 요청하며 주로
client
쪽에서 행에진다. 3way-handshaking
이때 발생한다.

int send(int socket, const char* data
int length, int flags)

-1 : 실패했을 경우
the # of byte :
성공했을 경우

Socket() : accept()에서 만들어진 descriptor
data : 
보내고 싶은 data
length : data
길이(byte)
flags :
대게 0으로 설정

상대방 프로그램에게 데이터를 송신한다.
만약 성공했을 경우 data TCP buffer 전송되었다는 것을 의미하며
전송 버퍼에 저장된 데이터는 ACK메세지를 수신하면서 삭제된다.


int recv(int socket, char*data,
int length, int flags)

Buffer 읽힌 byte
-1 :
에러가 생길 경우
0 :
접속종료를 알림

Socket : accept()에서 만들어진 descriptor
data :
수신받는 data
length : data
길이
flags :
대게 0으로 설정

Protocol(i.e : TCP) buffer 읽는 byte 읽는 함수이다.
stream
형식의 byte 읽는 것에 유의해야 하며 첫번째 parameter socket file descriptor(accept() 반환값)
임에 유의해야 한다.

int sendto(int socket, char* data,

Lint length, int flags,
struct sockaddr *destaddress,
int addresslen)

the # of byte : 성공했을 경우
-1 :
실패했을 경우

socket : accept() return
data :
원하는 data

length : data 길이
flags :
대게 0으로 설정
destaddress :
목적지의 address 가지고
                        
있는 구조체의 포인터
addresslen : destaddress
크기

Datagram 스타일의 전송방식으로써(datagram socket 다른 remote host 보지 못한다) 패킷을 전송하고
수신할 연결되지 않은 소켓을 통해 송신한다.
따라서 패킷을 보내기 destaddress 구조체를
이용하여 전송한다.

int recvform(int socket, char*data, lint length, int flags,
struct sockaddr *srcaddress,
int *addresslen)

Buffer 읽힌 byte
-1 :
에러가 생길 경우
0 :
접속종료를 알림

socket : accept() return
data :
원하는 data

length : data 길이
flags :
대게 0으로 설정
destaddress :
수신자의 address 가지고 있는
                         
구조체의 포인터
addresslen : destaddress
크기

Sendto() 형식과 같으며, 단지 receive() 하는
역할만이 다르다.

int setsockopt(int socket, int level,
int opt, const char* optval,
int optlen)

0 : 성공했을 경우
-1 :
실패했을 경우

Socket : socket() 반환값
level : SOL_SOCKET, IPPROTO_IP, IPPROTO_TCP
optval :
level == SOL_SOCKET ?
              SO_REUSEADDR  - IP addr/port
재사용
               SO_KEEPALIVE –
주기적 연결상태 확인
               SO_BROADCAST -
방송 전송 허용
               SO_LINGER - Closesocket()
처리 방식
               SO_SNDBUF -
송수신 버퍼 크기 설정

               SO_SNDTIME - 송수신 함수 타임아웃
level == IPPROTO_IP ?
               IP_TTL – TTL
설정

            IP_HDRINCL – 헤더 포함 전송
            IP_MULTUCAST_IF :
다중전송

 

생성된 소켓의 옵션을 설정하는 함수이다.

Parameter level opt 따라 결과 값이 바뀌게 된다.



int getsockopt(int socket, int level,
int opt, const char* optval,
int optlen)

0 : 성공했을 경우

-1: 실패했을 경우

setsockopt() 함수와 기본적으로 옵션이 같으며
opt
level 지정하면 원하는optval
값을 얻을 있다

소켓옵션을 확인하기 위한 함수이며, optval 값을 읽어드리며, 포인터로 지정한 변수에 값이 읽히게 된다.

struct hostent *gethostbyname(const char *name)

Struct hostent : 성공 했을 경우
서버에 관한 정보들이 구조체에 들어가게 된다.
NULL :
실패할 경우.

name : domain명을 적으면 된다.
             i.e) www.naver.com

도메인의 이름을 (ie. naver.com) 네트워크 바이트로
정렬된 2진수 IP주소로 변환한다. IPv6와의 호환성
때문에 최근에는 getaddrinfo() 혹은 getnameinfo() 쓴다

 

struct hostent *gethostbyaddr(const char *addr, int len, int type)

 

Struct hostent : 성공 했을 경우
서버에 관한 정보들이 구조체에 들어가게 된다.
NULL :
실패할 경우.

addr : IP 주소
len : IP
주소의 길이
type : IP
주소 type

이진수 IP주소를 도메인 이름으로 바꿔준다. 기본적인 개념은 gethostbyname()함수와 같다.


 

char *inet_ntoa(struct in_addr in);

int inet_aton(const char *cp,
struct in_addr *inp);

inet_ntoa()
     ip
주소 형태의 string 반환
 
 inet_aton()
     Non-zero :
주소가 valid 경우
     0 :
주소가 틀렸을 경우      

in : struct in_addr (ip주소를 담고 있는 구조체)
cp :
문자열 형태의 address
inp :
문자열 형태의 address IP형태로 변환할
        
저장될 struct in_addr 구조체

Number -> address, address -> number
변환이 필요할 쓰이며, 현재는 IPv6와의 호환성 때문에 inet_ntop() inet_pton()으로 대체되었다.

 

in_addr_t inet_addr(const char *cp);

 

주소 정보를 가지고 있는
in_addr_t
구조체를 반환한다.

cp : address 문자열

기본적으로 inet_aton() 함수와 같으며, 매우 오래된 method 쓰이지 않는다.

struct servent *getservbyname(                                                const char *name,                                            const char *proto)

 

servent  구조체가 반환되며, 만약 proto 값이 NULL 경우 protocol match되는 servent 구조체가 반환된다.

0 : 실패할경우 0 반환한다

name : servce 이름을 쓴다(program)
proto :
프로토콜 type 쓴다(TCP or UDP)

Parameter 주어진 이름과 프로토콜이 match되는
service
정보를 찾아서 정보를 가진servent 구조체로
반환하는 함수이다.

 

struct servent *getservbyport(int port, const char *proto);

 

servent  구조체가 반환되며, 만약 proto 값이 NULL 경우 protocol match되는 servent 구조체가 반환된다.

0 : 실패할경우 0 반환한다

port : 원하는 port # 쓴다.
proto : protocol type
쓴다(TCP or UDP)

 

기본적인 parameter getservbyname() 같다.

Paramter 주어진 port proto 매치되는 service정보를 찾아서 정보를 servent 구조체로 반환하는 함수이다.

uint32_t htonl(uint32_t hostlong);

uint16_t htons(uint16_t hostshort);

uint32_t ntohl(uint32_t netlong);

uint16_t ntohs(uint16_t netshort);

 

함수는 변환된 값을 반환한다.
uint32
4byte 의미하며
unint16
2byte 의미한다.

hostlong :  host long type 데이터
hostshort : host
short type 데이터
netlong : network
long type 데이터
netshort : network
short type 데이터

h : host 의미한다

to : converting 의미한다
n : network
의미한다
l,s :
데이터형을 의미한다
        (long or short)

host byte order로부터 network byte order

multi-byte integer type형식으로 변환한다.

(역도 성립한다, vice versa)

 

함수는 hardware 호환성 때문에 만들어 졌는데, 시스템 마다 각기 다른식으로 byte order 저장하기 때문에 port # 숫자를 네트워크로 전송 했을 경우 함수들을 써야한다.




struct for network-programming(네트워크 프로그래밍을 위한 구조체)

 

1.        struct sockaddr
{
    u_short sa_family;    /* address family */
    char sa_data[14];     /*
주소(IP 주소포트 번호) */
};

 

2.        struct in_addr            /* sockaddr_in 안에 정의되어 있음에 유의하자 */
{
    u_long s_addr;    /* 32
비트의 IP 주소를 저장할 구조체 */
}

 

3.        struct sockaddr_in
{
    short sin_family;            /*
주소 체계 */
    u_short sin_port;           /* 16
비트 포트 번호 */
    struct in_addr sin_addr; /* 32
비트 IP 주소 */
    char sin_zero[8];           /*
전체 크기를 16바이트로 맞추기 위한 dummy */
}


 

 

4.        struct hostent

{

    char *h_name            /*   host 이름 */

    char **h_aliases            /*  aliases(별명?) list , 마지막 요소는 항상 NULL이다 */

    int h_addrtype            /* address 형식 AF_INET 인터넷 주소 체계이다 */

    int length                    /* address 길이, byte단위 이다 */

    char **h_addr_list             /* IP주소의 list들이 있으며, struct in_addr* 가리키는 pointer이다.

}      

 

5.        struct servent
{

        char    *s_name;        /* 공식적인 service 이름*/

        char    **s_aliases;    /* alias(별명?) list */

        int     s_port;         /* port 번호 */

        char    *s_proto;       /* 사용하고 있는protocol  */
}


'Programming > Network Programming' 카테고리의 다른 글

.. no regret..  (0) 2011.10.26
The example of one server that sends a client ID  (0) 2011.10.15
get client IPadrress in server side  (0) 2011.10.10
TCP/IP  (0) 2011.09.21
The concept of TCP/IP part 1.  (2) 2011.09.07
Posted by 박세범
Programming/WinAPI2011. 9. 23. 01:23

Timer with Callback procedure using CreateTimerQueueTimer()

 

The prototype of CreateTimerQueueTimer supported by after windows 2000

BOOL WINAPI CreateTimerQueueTimer(
  __out     PHANDLE phNewTimer,
  __in_opt  HANDLE TimerQueue,
  __in      WAITORTIMERCALLBACK Callback,
  __in_opt  PVOID Parameter,
  __in      DWORD DueTime,
  __in      DWORD Period,
  __in      ULONG Flags
);

 

  1. phNewTimer : the handler that you want to use, ex) GetCurrentThread() means put the new-timer into the current thread.
  2. HANDLE TimerQueue : Optional, usually NULL , if it's null use a default Queue. 
  3. WAITORTIMERCALLBACK Callback : put the name of Callback function, the prototype of the Callback function is

    VOID CALLBACK WaitOrTimerCallback( __in  PVOID lpParameter, __in  BOOLEAN TimerOrWaitFired );

  4. Parameter : the parameter going to CALLBACK function int "lpParameter" (See above)
  5. Duetime : the amount of time in milliseconds relative to the current time, usually it's "0"
  6. Period : the period of the timer, in millisecond.(Elapse time)
  7. Flags : WT_EXECUTEDEFAULT, WT_EXECUTEINPERSISTENTTHREAD(very useful)

 

Example by Sebeom Park

 

struct ownDateSystem // Sebeom defined this.
{
 int date;
} oDate;

char str[9];	      // to save current SystemTime
SYSTEMTIME st;        // to get CurrentLocalTime of the system.

void CALLBACK TimerProc(PVOID lpParametar,BOOLEAN TimerOrWaitFired) // it works perfectly well
{
 int currentTime = GetCurrentLocalTime(st);		
 struct ownDateSystem *reservedStructure = (ownDateSystem *)lpParametar;	// casting from PVOID to "ownDateSystem"
 int reservedTime = reservedStructure->date;
 if(currentTime == reservedTime)
 {
 RunProcess("C:\\HNC\\Hwp70\\Hwp.exe",NULL);
 }
 else
 return;
 
 // MessageBox(NULL,"Hello","Hello",MB_OK);
} 


unsigned int GetCurrentLocalTime(SYSTEMTIME &st)		// get CurrentTime
{
 unsigned int currentTime;
 GetLocalTime(&st);
 wsprintf(str,"%d%d%d%d",st.wMonth,st.wDay,st.wHour,st.wMinute); // get the formet Month/Day/Hour/Min
 currentTime = atoi(str); // change the string to int
 return currentTime;
}



BOOL AddTimer(unsigned int setDate, HWND hWnd) // for testing.. practice
{
 oDate.date = 923038;
 HANDLE currentHandler = GetCurrentThread();

	
 CreateTimerQueueTimer(&currentHandler,NULL,TimerProc,&oDate,0,300,WT_EXECUTEDEFAULT); // Get Current Thread


 //wsprintf(str,"%d %d %d %d",st.wMonth,st.wDay,st.wHour,st.wMinute);
 return TRUE; 
}

'Programming > WinAPI' 카테고리의 다른 글

Practice  (0) 2011.09.04
Posted by 박세범

 Well. the reason why TCP/IP is very important is because that's the most common protocols now.

Let's take a look at the difference btw TCP and IP

Firstly IP is in a network layer, what's the purpose of this? it's a communication btw a computer and a computer
the answer why we use IP is because MAC cannot see other networks, that's why people need to make one
address that is able to look at other network's computers. THat's why IP came out.

In transport layer(Layer 4), there is one protocol named TCP.
TCP has some features as below.
  1) a communication btw apps and apps
  2) how do we know about app #? : using port number
  3) End to End, communication protocol... : it means using port, applications will reach to each other.

What's the roles of TCP?
   1) TCP is in Transport layer( #4 layer)
   2) Reliable data transmission
   3) End-to-end protocol
   4) Stream interface -> but the unit is a segment?
         -> What's stream? -> transmission by byte to byte.. when application will send a packet, it does not go to
             TCP segment directly, it goes to TCP buffer... the thing is TCP is variable that's why we do not know
             what size of data is coming. APP -> TCP buffer -> TCP -> Segment <-- converting
   5) connected oriented protocol : three ways hand shaking (very important, will be mentioned later)
   6) Full-duplex communication : it has both "direction" and "동시성(I don't know how to say)

End to End service : easily, it means an application of a host A is communicating with an application of host B
                             Connection -> Data sending -> Disconnecting.. think like a telephone
                             but TCP is just a virtual mechanism

How to be capsulated for TCP?

Frame(Ethernet) header + Datagram(IP) header + Segment(TCP)

TCP segment header 

1)     Source port(16bit) : 송신자의port넘버를 알기 위해서 정의된 field이다.

2)     Destination port(16bit) : 수신자의port 넘버를 알기 위해서 정의된 field이다.

3)     Sequence number : 2가지 역할을 하는데 SYN field값에 따라 다르다

a.      SYN == 1? : 이는initial sequence number로써, 처음 data byte Ack number 사용되어 진다. 이후 값들이 sequence 따라 1 증가하게 된다.

b.      SYN == 0?: 첫번째data byte  축적된 sequence number 의미한다.

4)     Acknowledgment number(32bit) : 만약 ackflagset 이라면, 값은 다음sequence number 의미한다. 상대방으롭터 다음 전송 때에 받기를 기대하는 첫째 바이트 번호이다.

5)     Data offset(4bit) : TCP header 크기를 구제화 시키는 field이다. Words(4byte) 단위로 구성되며 최대 20~60 byte까지 구성될 있다.

6)     Reserved (6bit): 미래에 사용될 것을 대비해서 착안됐으며, 0으로 set되어야 한다.

7)     Fags(6bit) : 6bits 구성되어 있으며,1bitflag 가지고 있다. 종류는 아래와 같다.

a.      URG flag : 긴급 상황이 발생했을 경우 사용된다.

b.     ACK flag : 전송된 값이 valid(유효함) 알리는데 사용된다.

c.      PSH flag : 버퍼가 차지 않았더라도, flag set이라면 바로 데이터를 전송한다.

d.     RST : 재설정(re-setting) 요구하는 flag이다.

e.     SYN : 3-way handshaking(Syn -> ack -> Syn 순서) 제의하는 flag이다.

f.       FIN : Session 종료하고자 사용한다.

g.      Window Size(16bit) : 현재 상태의 최대 버퍼크기를 말하는field이다.

h.     CheckSum : 데이터가 유효한 것인지, 이상이 없는지 확인하는field이다

i.        Urgent Pointer : 긴급한 데이터를 사용해야 데이터가 존재하는 곳을 가르키는 포인터 값이다.



 
  

'Programming > Network Programming' 카테고리의 다른 글

.. no regret..  (0) 2011.10.26
The example of one server that sends a client ID  (0) 2011.10.15
get client IPadrress in server side  (0) 2011.10.10
Reference for unix socket api  (0) 2011.09.29
The concept of TCP/IP part 1.  (2) 2011.09.07
Posted by 박세범
       
       
       
       
       
       


 From today, I am going to review all my studies at Dankook.
Today's topic is TCP/IP, which is the basis of network programming.

The teacher is Dr. 조경산. He is a excellent teacher =)

Basically, we need three elements, a sender, a receiver and a thing that connects between them
 so that network will work

What's the computer communication?
   : the computer, which equals with a receiver and sender or something related to computer.

 The important thing is why the computer communication has come out.
  1) Direct connection : just like word itself, it connects btw two computers directly by using a wire or physical stuff.
  2) Indirect connection : connecting all computers with a lot of networks, basically networks are connected.

 Direct connection costs a lot of money since everything would have to be closer and it also has a distance problem.

So, in order to do the indirect connection, we would have to make a rule so that all datas should have been sended and received perfectly against the direct connections.

we call the rule "protocol"

The definition of protocol is "a rule that is accepted in order to communicate between computer systems"
it consists of syntax, semantics, and timing.
syntax : the level of signal or data type.
semantics : the information for handling exceptions and each communications
timing : corresponding data speed and make an order


Now, important thing is "OSI7 layer protocol", which is a bit different from TCP/IP protocol

OSI 7 layer

Application(7)
Presentation(6)
Session(5)
Transport(4)
Network(3)
Data Link(2)
Physical(1)

However, TCP/IP has five layers.

application(5)
transport(4)
internet(3)
network interface(2)
physical(1)

since physical layer only hands the data transfer, we sometimes merge layer 1 and layer 2 as "network interface" itself.

We all data 'Packet' in network computing. but each layer has a different term indicating "Packet"
Network interface(2) -> frame
internet(3) -> Datagram
Transport(4) -> Segment.

Why we use TCP/IP? it's because..
"in order to treat internet easily.." is there anything more persuading than this?

based on OSI 7 layers concept, each layer except for physical layer will put one header each in the data.

 Layer 2
header
 Layer 3
header
Layer 4
header
 Layer 5
header
 Layer 6
header
  Layer 7
header
data


Well let's see "network interface layer(2)"

there is a Ethernet which is commonly used in Layer 2.

The structure of frame(= packet, called as "frame" in network interface layer.

Preamble
DA
SA
length
Data type
Data
CRC
IEEE 802.3 ethernet frame type

  Well. the structure is not a original data. it's been added with "header!" see a lot of headers, Preamble, DA, SA stuff like that.  look at the DA(Destination address)... what kind of address we use? IP? nope...
we use MAC(Media Access control address), which is a unique number of NIC(Network interface Card).
why do we use MAC? Layer 2 only cares about just one Network inside.
If there was no MAC, all data in one network would be sent to all computers in one network.
That's why we need MAC in order to look at the destination of the computer which we are supposed to send.

Loot at the CRC located in the end of a frame.
What's CRC firstly? -> Cyclic redundancy check, an error-detecting code designed to detect accidental changes to raw comtpuer data Wikipedia said.

Well. the thing why we need this is because Layer 1(physical) only care about transmitting all data bit by bit
in hardware perspective, the CRC must be handled in NIC(network interface card). it's more likely physical perspective.

lastly, take a look at length part. why do we need length? because.. there is no way how the computer would know
the length of a data. That's all.

let's move on the layer 3(internet layer).
we will see the concept of IP..
why did IP come out? it's because there was a problem between networks.
each network needed to transmit data to one another. but the thing is the media is different, form of frame is different..
that's why people though of making one virtual network which contains all networks.(let's see all networks as one network)

You know what?
All computers connected to the internet is connected to another network.(do you agree?)

as you know internet is a set of a lot of network. IP is the address which is uniquely possessed by a computer which
is connected to the internet.

now, there is new packet coming out, data gram...
IP is just one kind of protocols which defines the path of a destination from a sender.

Let's think about the difference btw MAC and IP(Internet protocol) addresses..
again, MAC is only used in one network inside, but IP is used from a network to network. Tha'ts the different.


What is the purpose of the internet? : virtual single communication system

 -> All hosts must use the same manner to make an address.
 -> the address must be unique
 -> IP address : independent address indicated(networks only recognize MAC address)
 -> usually 32 bit but IPv6 is 128 bits these days.. there is prefix and suffix.
in datagram header(it could be maximum 6k bytes(20+4n byte(header) + data)

there is one element of the header, TTL = Time to leave... -> why?
if a datagram(I mean packet) missed the way where it's supposed to be, then check the TTL in each network
net if the length is "1"?(from 255) then just throw it away because it took too long!

also there is CHECKSUM... it is implemented by a system.

Encapsulation.. you know the header will be put from Layer 5 to Layer 1 in Sender
and a destination take each one off from layer 1 to layer 5

ICMP(Internet Control Message Protocol)

IP has one characteristic.. which is best-effort, no matter what situations are, it doesn't matter
the purpose of IP is to transmit a data from sender to a receiver that's all.
it sometimes causes a error" but it doesn't matter

ICMP is purposed for the situation if IP layer(internet layer) has a problem in communications then
send a error msg to a destination.

so IP should be used with ICMP for handling errors..

'Programming > Network Programming' 카테고리의 다른 글

.. no regret..  (0) 2011.10.26
The example of one server that sends a client ID  (0) 2011.10.15
get client IPadrress in server side  (0) 2011.10.10
Reference for unix socket api  (0) 2011.09.29
TCP/IP  (0) 2011.09.21
Posted by 박세범