우분투 TCP server 예제
server.c
#include <stdio.h>
#include <stdlib>
#include <string.h>
#include <time.h>
#include <unustd.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#define BUF_LEN 128
int main(int argc,char *argv[])
{
char buffer[BUF_LEN];
struct sockaddr_in server_addr,client_addr;
char temp[20];
int server_fd,client_fd;
int len,msg_size;
char test[20];
int i = 0;
if(argc !=2)
{
printf("Usege ./filename [PORT] \n");
exit(0);
}
//socket 생성
if((server_fd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
printf("Server: can not Open Socket\n");
exit(0);
}
memset(&server_addr,0x00,sizeof(server_addr));
server_addr.sin_family = AF_INET;
// server_addr.sin_addr.s_addr = inet_addr(argv[2]);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
// server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//
//servwe_addr.sin_port = htons(atoi("1234"));
server_addr.sin_port = htons(atoi(argv[1]));//
// bind 부분
if(bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr))< 0)
{
printf("Server: cat not bind local addrss\n");
exit(0);
}
//listen 부분
if(listen(server_fd,5) < 0)
{
printf("Server: cat not listen connnect.\n");
exit(0);
}
memset(buffer,0x00,sizeof(buffer));
len = sizeof(client_addr);
printf("=====[PORT] : %d =====\n",atoi(argv[1]));
printf("Server : wating connection request.\n");
while(1)
{
printf("-------------------------\n");
//accept 부분
client_fd = accept(server_fd,(struct sockaddr *)&client_addr,(socklen_t *)&len);
if(client_fd < 0)
{
printf("Server: accept failed\n");
exit(0);
}
inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,temp,sizeof(temp));
printf("Server: %s client connect.\n",temp);
send(client_fd,"abcde",0xff,0);
msg_size = recv(client_fd,(char *)buffer,BUF_LEN,0);
send(client_fd,(char *)buffer,msg_size,0);
printf("Server: %s client closed.\n",temp);
close(client_fd);
}
close(server_fd);
return 0;
}
컴파일 후 PORT 번호를 1234
'space' 카테고리의 다른 글
문제 (1) | 2020.02.06 |
---|---|
우분투 TCP 클라이언트 예제 <client> (0) | 2020.02.06 |
OSI 7 Layer 표 (0) | 2020.02.06 |
IoT 네트워크 및 통신 프로토콜 (0) | 2020.02.05 |
MQTT 해보기 (0) | 2020.02.05 |