'2019/05/24'에 해당되는 글 4건

  1. 2019.05.24 cpp stringstream << 연산자
  2. 2019.05.24 리눅스 UDP 소켓
  3. 2019.05.24 while(-1) 이 될까?
  4. 2019.05.24 리눅스 TCP 소켓
Programming/C++ STL2019. 5. 24. 15:43

어떻게 보면.. scanf를 좀 편리하게 해주는 cpp용 연산자라고 보면 되려나?

 

[링크 : http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/]

 

string str_sensor_data(mesg);
stringstream stream(str_sensor_data);
for(int i=0;i<5;i++){

    stream >> sensor_data[i]; 

}

[링크 : http://youngmok.com/udp-server-c-class-listening-thread/]

'Programming > C++ STL' 카테고리의 다른 글

cpp 부모타입으로 업 캐스팅 된 객체의 원래 클래스 알기  (0) 2021.09.30
cpp string 관련  (0) 2019.06.10
c++ 함수 인자 기본값  (0) 2017.11.08
cpp string compare 와 ==  (0) 2017.01.31
cpp this  (0) 2016.07.18
Posted by 구차니
Linux API/network2019. 5. 24. 14:11

sento() 에 인자를 좀 바꾸어서 명령어줄 인자를 받으면 재미있긴 한데..

TCP 처럼 클라이언트 별로 accept 해주는 구조가 아니라

개별 클라이언트를 어떻게 구분해야 하지? 라고 고민중

 

server

// Server side implementation of UDP client-server model
#include 
#include 
#include 
#include 
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT     8080
#define MAXLINE 1024

// Driver code
int main() {
        int sockfd;
        char buffer[MAXLINE];
        char *hello = "Hello from server";
        struct sockaddr_in servaddr, cliaddr;

        // Creating socket file descriptor
        if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
                perror("socket creation failed");
                exit(EXIT_FAILURE);
        }

        memset(&servaddr, 0, sizeof(servaddr));
        memset(&cliaddr, 0, sizeof(cliaddr));

        // Filling server information
        servaddr.sin_family = AF_INET; // IPv4
        servaddr.sin_addr.s_addr = INADDR_ANY;
        servaddr.sin_port = htons(PORT);

        // Bind the socket with the server address
        if ( bind(sockfd, (const struct sockaddr *)&servaddr,
                        sizeof(servaddr)) < 0 )
        {
                perror("bind failed");
                exit(EXIT_FAILURE);
        }

        while(1)
        {
        int len, n;
        n = recvfrom(sockfd, (char *)buffer, MAXLINE,
                                MSG_WAITALL, ( struct sockaddr *) &cliaddr,
                                &len);
        buffer[n] = '\0';
        printf("Client : %s\n", buffer);
//      sendto(sockfd, (const char *)hello, strlen(hello),
        sendto(sockfd, (const char *)buffer, strlen(buffer),
                MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
                        len);
        printf("Hello message sent.\n");
        }
        return 0;
}

 

client

// Client side implementation of UDP client-server model
#include 
#include 
#include 
#include 
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT     8080
#define MAXLINE 1024

// Driver code
int main(int argc, char **argv) {
        int sockfd;
        char buffer[MAXLINE];
        char *hello = "Hello from client";
        struct sockaddr_in       servaddr;

        // Creating socket file descriptor
        if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
                perror("socket creation failed");
                exit(EXIT_FAILURE);
        }

        memset(&servaddr, 0, sizeof(servaddr));

        // Filling server information
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(PORT);
        servaddr.sin_addr.s_addr = INADDR_ANY;

        int n, len;

//      sendto(sockfd, (const char *)hello, strlen(hello),
        sendto(sockfd, (const char *)argv[1], strlen(argv[1]),
                MSG_CONFIRM, (const struct sockaddr *) &servaddr,
                        sizeof(servaddr));
        printf("Hello message sent.\n");

        n = recvfrom(sockfd, (char *)buffer, MAXLINE,
                                MSG_WAITALL, (struct sockaddr *) &servaddr,
                                &len);
        buffer[n] = '\0';
        printf("Server : %s\n", buffer);

        close(sockfd);
        return 0;
}

 

[링크 : https://www.geeksforgeeks.org/udp-server-client-implementation-c/]

[링크 : https://www.geeksforgeeks.org/tcp-and-udp-server-using-select/]

 

+

[링크 : https://scrapsquare.com/notes/udp-length]

[링크 : https://en.wikipedia.org/wiki/User_Datagram_Protocol]

 

+

class (cpp) 기반 UDP socket 예제

[링크 : http://youngmok.com/udp-server-c-class-listening-thread/]

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

UDS (Unix Domain Socket)  (0) 2020.09.01
raw socker과 promiscous mode  (0) 2019.07.03
리눅스 TCP 소켓  (0) 2019.05.24
linux udp cpp example  (0) 2019.05.16
linux socket 관련  (0) 2015.01.22
Posted by 구차니
Programming/C Win32 MFC2019. 5. 24. 12:18

코드 분석하다 보니 어떻게 작동할지 몰라서 해보니

헐.. while(0) 이냐 !0 이냐 정도로 밖에 작동하지 않네

예제 소스가 이상한 조건문이 되어버렸네...

 

client_sock에 -1이 들어와도 while은 중단되지 않고 0일때만 중단되는데

그러면 if(client_sock < 0)은 <=0이 아니라 들어갈 방법이 없네?

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;
}

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

'Programming > C Win32 MFC' 카테고리의 다른 글

vkey win32 / linux  (0) 2021.04.30
strptime  (0) 2021.02.17
c언어용 JSON 라이브러리 목록  (0) 2018.10.23
uuid in c  (0) 2018.10.22
엔디안 급 멘붕..  (0) 2018.05.29
Posted by 구차니
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 구차니