errno
errno - 에러가 나면 에러에 대한 번호를 리턴해줌.
bind(소켓 번호, 구조체주소(내 주소 및 server 주소))
소켓과 내 주소를 결합시킬 때 쓰이는 함수가 bind함수이다.
listen(소켓번호, 대기큐, ) - 첫 번째 인자 소켓번호, 대기큐는 두 번째 인자 보통 5라고 적는다.
accept()
blocking함수는 scanf도 포함.(키보드를 입력받을 때까지 대기타니까.)
non blocking함수는 printf등등
server
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/types.h>
#include <netinet/in.h>
#include <errno.h>
int main()
{
struct sockaddr_in stAddr; //server addr
struct sockaddr_in stClient1;
int iSoc; //socket descripter
int iCle1;
int iRet;
unsigned int uiSize;
iSoc = socket(AF_INET, SOCK_STREAM, 0);
if(-1==iSoc)
{
perror("socket() ");
return 0;
}
stAddr.sin_family = AF_INET;
//소켓의 첫 번째 인자를 넣는다.
stAddr.sin_port = htons(PORT);
stAddr.sin_addr.s_addr = inet_addr("192.168.10.250");
iRet=bind(iSoc, (struct sockaddr *)(&stAddr),sizeof(stAddr));
//bind() 함수는 소켓 IP주소와 포트번호를 지정해 준다.
//이로써 소켓을 통신에 사용할 수 있도록 준비됨.
if(iRet!=0)
{
perror("bind() ");
close(iSoc);
return 0;
}
iRet=listen(iSoc,5);
//두 번째 인자는 대기자 인원 나머지는 refuse connect
//listen()함수는 소켓을 통해 클라이언트의 접속 요청을 기다리도록 설정.
if(iRet!=0)
{
perror("listen() ");
close(iSoc);
return 0;
}
uiSize=sizeof(stClient1);
iCle1=accept(iSoc,(struct sockaddr *)(&stClient1),&uiSize);
//클라이언트의 인적사항 조사 accept가 리턴되면 새로운 소켓을 생성한다.
//클라이언트의 접속 요청을 받아들이고 클라이언트와 통신하는 전용 소켓을 생성한다.
//반환값으로 새로운 소켓을 생성.
if(iCle1!=0)
{
perror("accept() ");
close(iSoc);
return 0;
}
printf("iSoc : %d\niRet : %d \n",iSoc, iRet);
printf("iCle1 : %d\n",iCle1);
close(iSoc);
close(iCle1);
return 0;
}
client
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/types.h>
#include <netinet/in.h>
#include <errno.h>
int main()
{
struct sockaddr_in stAddr;
int iSoc;
int iRet;
iSoc = socket(AF_INET, SOCK_STREAM, 0);
if(-1==iSoc)
{
perror("socket() ");
return 0;
}
stAddr.sin_family = AF_INET;
//소켓의 첫 번째 인자를 넣는다.
stAddr.sin_port = htons(PORT);
stAddr.sin_addr.s_addr = inet_addr("192.168.10.250");
iRet=connect(iSoc, (struct sockaddr *)(&stAddr),sizeof(stAddr));
if(iRet!=0)
{
perror("connect() "); //나머지 에러 내용을 peeror이 출력해줌.
close(iSoc);
return 0;
}
printf("iSoc : %d\n iRet : %d \n",iSoc, iRet);
close(iSoc);
return 0;
}
'네트워크' 카테고리의 다른 글
20140618 - TCP 3 Way Handshake, TCP Four-way handshaking, 멀티 프로세스 생성하기 (0) | 2014.06.18 |
---|---|
20140617 - 소켓 정보보내기(서버, 클라이언트) (0) | 2014.06.17 |
20140613 - 소켓 통신(소켓 생성), socket client source (0) | 2014.06.13 |
20140611 - 네트워크 기본 개념, 기본 네트워크 프로그래밍 (0) | 2014.06.11 |
20140610 - 네트워크 개념 (0) | 2014.06.10 |