Skip to main content
GameDev.net gamedev.net
🔒 Locked

getting sockets to work

Started by Sagar_Indurkhya Dec 21, 2008 at 3:26 PM 0 replies 750+ views
Original Post
Sagar_Indurkhya
Sagar_Indurkhya
I'm trying to write two programs, a C program and a Scheme program that can talk to each other using sockets. The Scheme program acts as the server, and the C program as the client. I can get it to work if the Scheme program acts as the client and the C program as the server, but not the other way around. Is there anything obvious I'm missing? The C Client program:

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

using namespace std;


#define SERVER_IP	"127.0.0.1"
#define ADDR_LEN	(sizeof(struct sockaddr))
#define PORT		20000

extern int errno;

int main() {
	int fd_client;
	struct sockaddr_in serv_addr;
	char buf[256];
	int check_ret;

	buf[0] = '\0';
	
	fd_client = socket(AF_INET, SOCK_STREAM, 0);
	if(fd_client < 0) {
		printf("error creating socket. errno is %d\n", errno);
		exit(1);
	}

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

	bzero(&(serv_addr.sin_zero), 8);

	check_ret = connect(fd_client, 
			(struct sockaddr *) &serv_addr, ADDR_LEN);
	if(check_ret < 0) {
		printf("Connect error. Errno is %d\n", errno);
		exit(1);
	}

	cout << "Entering read loop..." << std::endl;
	
	while(1) {
		printf("READ : ");
		read(fd_client, buf, 256);
		printf("%s", buf);
		bzero(buf, 256);
	}

	return 0;
}

and the scheme server program:

(define mySS (open-tcp-server-socket 20000))
(define myPort (tcp-server-connection-accept mySS #t #f))
(write-char #\z myPort)
(flush-output myPort)
; stuff should appear on the client side now!

alvaro
alvaro
I usually test TCP clients by having them connect to well-established servers. For instance, you can connect to port 13 (daytime) of a time server (I used 192.43.244.18, which is time.nist.gov). That protocol is dead simple, where you connect and you can immediately read some text from the server.

The only thing in your client that doesn't quite work is that you don't detect if the socket has been closed (read returns 0), so you enter an infinite loop.

By the way, your client is written in C++, not in C. These are different programming languages.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.