I'm trying to write a pair of classes (a client and a server) that can communicate with each other.

I am relativly new to C so any pointers would be great! My simple server code (server.c) so far is:

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

void main()
{
	int fd;
	fd = socket(AF_INET,SOCK_STREAM,0);
	
	struct sockaddr_in addr;
	inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(5000);
	
	if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1){
		printf("S:ERROR BINDING SOCK\n");
		close(fd);
	}

	if (listen(fd, 5) == -1){
		printf("S:ERROR LISTENING\n");
		close(fd);
	}
	else {
		printf("S:RUNNING...\n");
	}
	
	int connfd;
	struct sockaddr_in cliaddr;
	socklen_t cliaddrlen = sizeof(cliaddr);

	connfd = accept(fd, &cliaddr, &cliaddrlen);

	if (connfd == -1){
		printf("ERROR ACCEPTING CONNECTION\n");
		close(fd);
	}
	else {
		printf("S: accepted connection...");
	}
}

And my client code is (client.c):

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

void main()
{
	int fd;
	fd = socket(AF_INET,SOCK_STREAM,0);
	
	struct sockaddr_in addr;
	inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(5000);

	if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1){
		printf("ERROR CONNECTING SOCK\n");
	}
	else {
		printf("C:ATTEMPTING TO CONNECT...\n");
	}

}

How can i set the classes up to communicate with each other? Is the problem my addesses? Or does it have to be done on different computers?

Thanks,

Logi.

This article has been dead for over six months. Start a new discussion instead.