LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 01-01-2020, 11:46 AM   #1
end
Member
 
Registered: Aug 2016
Posts: 266

Rep: Reputation: Disabled
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);




	}
	
	
}
 
Old 01-01-2020, 12:47 PM   #2
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
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.
 
1 members found this post helpful.
Old 01-02-2020, 07:25 AM   #3
end
Member
 
Registered: Aug 2016
Posts: 266

Original Poster
Rep: Reputation: Disabled
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);		
		



	}
	
	
}
 
Old 01-02-2020, 08:27 AM   #4
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
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);
}

Last edited by SoftSprocket; 01-02-2020 at 08:29 AM.
 
1 members found this post helpful.
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Howe to dual boot on mac -- elementary os Straitsfan Linux - Newbie 1 09-27-2016 03:43 AM
Sendmail: unable to send and recive email in intranet nikhilgeo Red Hat 3 06-22-2011 12:30 AM
Linux Email client to send/recive mails from Exchange server Hussain000 Red Hat 1 01-01-2009 05:41 AM
can send mails, can't recive them (mailscanner+postfix+dovecot) chuck_cts Linux - Networking 2 04-05-2008 08:10 AM
unable to send/recive msg thru thunderbird jabka Mandriva 0 10-18-2005 04:37 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 02:48 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration