프로젝트 자료실

linux Socket Server

작성자 임베디드코리아 작성일21-06-15 14:34 조회1,719회 댓글0건
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#define MAXBUF 1024

int main(int argc, char **argv)
{
int server_sock;
int client_sock;
char read_BUF[MAXBUF];
char sendMessage[MAXBUF];
unsigned int ClientAddr_size;
char ch_quit;

struct sockaddr_in ServerAddr;
struct sockaddr_in ClientAddr;

/*서버 소켓 생성*/
server_sock = socket(PF_INET, SOCK_STREAM, 0);

if(server_sock == -1)
{
perror("sock()");
close(server_sock);
return 0;
}
// printf("socket() : domain = %d\n", server_sock);

/*소켓에 주소 할당*/
memset(&ServerAddr, 0, sizeof(ServerAddr));
ServerAddr.sin_family = AF_INET;
// ServerAddr.sin_port = htons(4030);
ServerAddr.sin_port = htons(atoi(argv[1]));
// ServerAddr.sin_addr.s_addr = inet_addr("211.220.225.30");
// ServerAddr.sin_addr.s_addr = inet_addr(argv[2]);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);

if(bind(server_sock, (struct sockaddr*)&ServerAddr, sizeof(ServerAddr)) == -1)
{
perror("bind() ");
close(server_sock);
return 0;
}

/*연결 요청 대기 상태로 진입*/
if(listen(server_sock, 5) == -1)
{
perror("listen() ");
close(server_sock);
return 0;
}

/*연결 요청 수락*/
ClientAddr_size = sizeof(ClientAddr);
client_sock = accept(server_sock, (struct sockaddr*)&ClientAddr, &ClientAddr_size);
// printf("accept() : return = %d\n", client_sock);

if(0 > client_sock)
{
perror("accept() ");
close(server_sock);
close(client_sock);
return 0;
}
while(1)
{
memset(read_BUF, 0, sizeof(read_BUF));
memset(sendMessage, 0, sizeof(sendMessage));
/*데이터 수신*/
recv(client_sock, read_BUF, sizeof(read_BUF), 0);
printf("client : %s \n", read_BUF);

/*데이터 전송*/
printf("server seyoung send message : ");
scanf("%s", sendMessage);

strncpy(&ch_quit, sendMessage, 1);
if(ch_quit == 'q')
{
break;
}
// write(client_sock, "WELCOME SEYOUNG", 33);
write(client_sock, sendMessage, sizeof(sendMessage));
}
/*연결 종료*/
close(client_sock);
close(server_sock);
return 0;
}