Linux에서 Socket 프로그래밍의 간단한 예

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define SERVPORT 3333 
#define BACKLOG 10 
main()
{
 int sockfd,client_fd ,sin_size; 
struct sockaddr_in my_addr; 
struct sockaddr_in remote_addr; 
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 
{
 perror("socket error"); exit(1);
 }
 my_addr.sin_family=AF_INET;
 my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
 bzero(&(my_addr.sin_zero),8);
 if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) 
{
 perror("bind error");
 exit(1);
 }
 if (listen(sockfd, BACKLOG) == -1) 
{
 perror("listen error");
 exit(1);
 }
 while(1) {
 sin_size = sizeof(struct sockaddr_in);
 if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) == -1) 
{
 perror("accept error");
 continue;
}
 printf("received a connection from %s
", inet_ntoa(remote_addr.sin_addr)); if (!fork()) { time_t timep; time (&timep); char temp[100]="Hello,you are connected!the time now is:"; char * t=ctime(&timep); strcat(temp,t); if (send(client_fd, temp, 100, 0) == -1) perror("send error"); close(client_fd); exit(0); } close(client_fd); } }

설명: 서버에서 이 서비스를 먼저 시작하고 클라이언트가 방문할 수 있습니다.텔넷 서버 IP 3333(포트) 사용 가능
 
수정 버전:
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define SERVPORT 3333 
#define BACKLOG 10 
main()
{
 int sockfd,client_fd ,sin_size; 
struct sockaddr_in my_addr; 
struct sockaddr_in remote_addr; 
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 
{
 perror("socket error"); exit(1);
 }
 my_addr.sin_family=AF_INET;
 my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
 bzero(&(my_addr.sin_zero),8);
 if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) 
{
 perror("bind error");
 exit(1);
 }
 if (listen(sockfd, BACKLOG) == -1) 
{
 perror("listen error");
 exit(1);
 }
 while(1) {
 sin_size = sizeof(struct sockaddr_in);
 if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) == -1) 
{
 perror("accept error");
 continue;
}
 printf("received a connection from %s
", inet_ntoa(remote_addr.sin_addr)); if (!fork()) { time_t timep; time (&timep); char temp[1024]="\r
\r
:"; char * t=ctime(&timep); strcat(temp,t); strcat(temp,""); send(client_fd,"HTTP/1.1 200 OK\r
Server:HWS\r
Content-Length:1024\r
Content-Type:text/html;charset=utf-8\r
", 90, 0); send(client_fd, temp, 1024, 0); close(client_fd); exit(0); } close(client_fd); } }

좋은 웹페이지 즐겨찾기