LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Howe implement while loop for send and recive message in c (https://www.linuxquestions.org/questions/programming-9/howe-implement-while-loop-for-send-and-recive-message-in-c-4175666861/)

end 01-01-2020 11:46 AM

Howe implement while loop for send and recive message in c
 
hi

howe in while loop make comunication boath side automatic i need press enter or send message to recive message. i test it with netcat nc and canot recive message before i send. howe to write while loop.


Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include<arpa/inet.h>



int main(int argc , char *argv[]  )
{
        int sockett;
        struct sockaddr_in server;
        char buffer[1024];       
        char bufferr[1024];       
        int rcv;

        sockett=socket(AF_INET, SOCK_STREAM,0);

        server.sin_family=AF_INET;
        server.sin_port= htons(80);
        server.sin_addr.s_addr =inet_addr(argv[1]);

        int ret =-1;
        ret = connect(sockett, (struct sockaddr *)&server, sizeof(struct sockaddr_in));

       


        while(1 )
        {       
               
                if( recv(sockett,buffer,1024,0) >0 )
                        printf("%s",buffer);

               
               
                if (send(sockett,bufferr,strlen(bufferr),0) >0 )
                        scanf("%s",bufferr,1024);




        }
       
       
}


SoftSprocket 01-01-2020 12:47 PM

You should read the manpage for each of the system calls you are making. You need to be checking the return values so you can tell if they are succeeding before proceeding.

Reading the manpage will also give you an idea of what to expect from the call. For instance, unless the sockoption is set to make recv non-blocking it will block until data arrives.

Sockets can be used to communicate between threads or processes which is not what you are doing here. After reading some more you will probably want to divide your program into a client and a server program and try again.

-Greg.

end 01-02-2020 07:25 AM

hi
 
hi i try with nonblocking on socket with fcntl but then i get connect error from connect()

i try with this also but same connect() error.

Code:

sockett=socket(AF_INET,SOCK_STREAM | SOCK_NONBLOCK ,0);

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include<arpa/inet.h>
#include <fcntl.h>


int main(int argc , char *argv[]  )
{
        int sockett;
        struct sockaddr_in server;
        char buffer[1024];       
        char bufferr[1024];       
        int nonb;

        sockett=socket(AF_INET,SOCK_STREAM ,0);

        nonb=fcntl(sockett,F_SETFL, O_NONBLOCK);

        server.sin_family=AF_INET;
        server.sin_port= htons(80);
        server.sin_addr.s_addr =inet_addr(argv[1]);

        int ret;
        ret = connect(sockett, (struct sockaddr *)&server, sizeof(struct sockaddr_in));

        if (sockett<0)
                printf("SOCKET ERROR\n");

        if (ret<0)
                printf("CONNECT ERROR\n\n");
       

        if(nonb<0)
                printf("NONBLOCK ERROR");



        while(recv(sockett, buffer, 1024, 0) >0)
        {
                    printf(" %s\n",buffer);               
               



        }
       
       
}


SoftSprocket 01-02-2020 08:27 AM

You'd do well to read a good tutorial on client/server socket programming. There area some concepts you'll need to go forward but I'll try to summarize some.

There are different protocols used in socket communication. The primary socket types are the datagram and stream sockets (UDP and TCP respectively) and the domains are unix/local or internet.

TCP is a connected protocol and that is what SOCK_STREAM refers to. AF_INET is the internet (inet) domain for v4 internet addresses.

A basic TCP internet server will request a socket descriptor from the operating system (man 2 socket), bind the socket descriptor to a sockaddr (man 2 bind), convert the socket to a listening socket (man 2 listen) and then signal the operating system readiness to accept connections (man 2 accept). After accepting a connection the server will read and write according to whatever protocol is being used.

There, of course, are many variations to this.

Here's an example I keep hanging around on my hard drive. It accepts either v4 or v6 addresses and can be terminated by sending it a sighup. If you compile and run it form a command line, with a port as an argument, then point a browser at it you get hello world for your troubles.

Code:


#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <error.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>


int stop = 0;
void signal_handler (int n) {
        stop = 1;
}

int main (int argc, char* argv[]) {
        if (argc != 2) {
                fprintf(stderr, "Usage: %s port\n", argv[0]);
                exit(EXIT_FAILURE);
        }

        int sd = socket (AF_INET6, SOCK_STREAM, 0);
        if (sd < 0) {
                perror ("socket");
                exit (EXIT_FAILURE);
        }

        int state = 1;

        int rv = setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, &state, sizeof state);
        if (rv < 0) {
                perror ("setsockopt");
                exit (EXIT_FAILURE);
        }

        struct sockaddr_in6 serveraddr;

        memset (&serveraddr, 0, sizeof serveraddr);
        serveraddr.sin6_family = AF_INET6;
        serveraddr.sin6_port = htons (atoi (argv[1]));
        serveraddr.sin6_addr = in6addr_any;

        rv = bind (sd, (struct sockaddr*) &serveraddr, sizeof (serveraddr));
          if (rv < 0) {
                perror ("bind");
                exit (EXIT_FAILURE);
        }

        rv = listen (sd, 10);               
        if (rv < 0) {
                perror ("listen");
                close (sd);
                exit (EXIT_FAILURE);
        }

        struct sigaction sa;

        sigaction (SIGHUP, NULL, &sa);

        if (sa.sa_handler != SIG_IGN)
        {
                sa.sa_handler = signal_handler;
                sigemptyset (&sa.sa_mask);
                sigaction (SIGHUP, &sa, NULL);
        }

        while (!stop) {
                int conn_sd = accept (sd, NULL, NULL);
                if (conn_sd < 0) {
                        perror ("accept");
                        continue;
                }

                struct sockaddr_in6 client_sockaddr;
                socklen_t sl = sizeof client_sockaddr;
                getpeername (conn_sd, (struct sockaddr*) &client_sockaddr, &sl);
               
                char addr_str[INET6_ADDRSTRLEN];
                if(inet_ntop(AF_INET6, &client_sockaddr.sin6_addr, addr_str, sizeof addr_str)) {
                        printf("Client address is %s\n", addr_str);
                        printf("Client port is %d\n", ntohs(client_sockaddr.sin6_port));
                }

                char recv_buf[2056];
                int n = 0;
                while ((n = recv (conn_sd, recv_buf, sizeof recv_buf, 0)) > 0) {
                        recv_buf[n] = '\0';
                        printf ("%s", recv_buf);
                        if ((recv_buf[n - 1] == '\n' && recv_buf[n - 2] == '\n')
                                        || (recv_buf[n - 1] == '\n' && recv_buf[n - 2] == '\r' && recv_buf [n - 3] == '\n' && recv_buf [n - 4] == '\r')) {
                                        break;
                        }
                }

                printf ("\n");

                if (n < 0) {
                        perror ("recv");
                        close (conn_sd);
                        continue;
                }

                char* msg = "Hello World!\n";

                int len = strlen (msg);
       
                char* pmsg = msg;
                while ((n = send (conn_sd, pmsg, len, 0)) < len) {
                        if (n == -1) {
                                perror ("send");
                                close (conn_sd);
                                continue;
                        }

                        pmsg += n;
                        len -= n;       
                }

                close (conn_sd);
        }       


        close (sd);

        exit (EXIT_SUCCESS);
}



All times are GMT -5. The time now is 07:26 AM.