Linux API/network2019. 5. 24. 11:01

개념만 알지 써보진 않은 녀석이라.. 후 공부 해야겠네 ㅠㅠ

역시 공부는 돈받고 해야 제맛

 

테스트 삼아 SOCK_STREAM을 SOCK_DGRAM 으로 바꾸었는데

accept 하는 부분이 달라져야 하는지 정상작동을 하진 않는다.

(댓글들 보면 메모리 누수라던가 여러가지 문제가 넘치는 소스인듯)

그래도 서버 하나 실행하고 클라이언트 여러개 실행해도 각각 응답이 다르게 오는것 봐서는

내가 의도하는 그런 정상적인(!) 서버로 구동되는 건 맞는 듯 하니 일단 패스

 

server

/*
        C socket server example, handles multiple clients using threads
*/

#include
#include      //strlen
#include      //strlen
#include<sys/socket.h>
#include<arpa/inet.h>   //inet_addr
#include      //write
#include //for threading , link with lpthread

//the thread function
void *connection_handler(void *);

int main(int argc , char *argv[])
{
        int socket_desc , client_sock , c , *new_sock;
        struct sockaddr_in server , client;

        //Create socket
        socket_desc = socket(AF_INET , SOCK_STREAM , 0);
        if (socket_desc == -1)
        {
                printf("Could not create socket");
        }
        puts("Socket created");

        //Prepare the sockaddr_in structure
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = INADDR_ANY;
        server.sin_port = htons( 8888 );

        //Bind
        if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
        {
                //print the error message
                perror("bind failed. Error");
                return 1;
        }
        puts("bind done");

        //Listen
        listen(socket_desc , 3);

        //Accept and incoming connection
        puts("Waiting for incoming connections...");
        c = sizeof(struct sockaddr_in);


        //Accept and incoming connection
        puts("Waiting for incoming connections...");
        c = sizeof(struct sockaddr_in);
        while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
        {
                puts("Connection accepted");

                pthread_t sniffer_thread;
                new_sock = malloc(1);
                *new_sock = client_sock;

                if( pthread_create( &sniffer_thread , NULL ,  connection_handler , (void*) new_sock) < 0)
                {
                        perror("could not create thread");
                        return 1;
                }

                //Now join the thread , so that we dont terminate before the thread
                //pthread_join( sniffer_thread , NULL);
                puts("Handler assigned");
        }

        if (client_sock < 0)
        {
                perror("accept failed");
                return 1;
        }

        return 0;
}

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
        //Get the socket descriptor
        int sock = *(int*)socket_desc;
        int read_size;
        char *message , client_message[2000];

        //Send some messages to the client
        message = "Greetings! I am your connection handler\n";
        write(sock , message , strlen(message));

        message = "Now type something and i shall repeat what you type \n";
        write(sock , message , strlen(message));

        //Receive a message from client
        while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
        {
                //Send the message back to client
                write(sock , client_message , strlen(client_message));
        }

        if(read_size == 0)
        {
                puts("Client disconnected");
                fflush(stdout);
        }
        else if(read_size == -1)
        {
                perror("recv failed");
        }

        //Free the socket pointer
        free(socket_desc);

        return 0;
}

client

/*
        C ECHO client example using sockets
*/
#include       //printf
#include      //strlen
#include<sys/socket.h>  //socket
#include<arpa/inet.h>   //inet_addr
#include 

int main(int argc , char *argv[])
{
        int sock;
        struct sockaddr_in server;
        char message[1000] , server_reply[2000];

        //Create socket
        sock = socket(AF_INET , SOCK_STREAM , 0);
        if (sock == -1)
        {
                printf("Could not create socket");
        }
        puts("Socket created");

        server.sin_addr.s_addr = inet_addr("127.0.0.1");
        server.sin_family = AF_INET;
        server.sin_port = htons( 8888 );

        //Connect to remote server
        if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
        {
                perror("connect failed. Error");
                return 1;
        }

        puts("Connected\n");

        //keep communicating with server
        while(1)
        {
                printf("Enter message : ");
                scanf("%s" , message);

                //Send some data
                if( send(sock , message , strlen(message) , 0) < 0)
                {
                        puts("Send failed");
                        return 1;
                }

                //Receive a reply from the server
                if( recv(sock , server_reply , 2000 , 0) < 0)
                {
                        puts("recv failed");
                        break;
                }

                puts("Server reply :");
                puts(server_reply);
        }

        close(sock);
        return 0;
}

[링크 : https://www.geeksforgeeks.org/...-handling-multiple-clients-on-server-without-multi-threading/]

[링크 : https://stackoverflow.com/questions/31461492/client-server-multiple-connections-in-c]

 

1. Create socket
2. Bind to address and port
3. Put in listening mode
4. Accept connections and process there after.

[링크 : https://www.binarytides.com/server-client-example-c-sockets-linux/]

 

 

+

man page 보는데 특이하게 2번과 3번으로 두개가 있네?

설명 자체는 둘이 좀 달라서 어느게 어떤 차이가 있는지 좀 애매하다.

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

#define _GNU_SOURCE
            /* See feature_test_macros(7) */

#include <sys/socket.h>

int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags);

[링크 : https://linux.die.net/man/2/accept]

 

#include <sys/socket.h>

int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len);

[링크 : https://linux.die.net/man/3/accept]

 

 

'Linux API > network' 카테고리의 다른 글

raw socker과 promiscous mode  (0) 2019.07.03
리눅스 UDP 소켓  (0) 2019.05.24
linux udp cpp example  (0) 2019.05.16
linux socket 관련  (0) 2015.01.22
멀티캐스트 되는지 여부 확인  (0) 2014.11.21
Posted by 구차니