Jump to content
  • Advertisement
Sign in to follow this  

getting sockets to work

This topic is 3591 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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	""
#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);

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

	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!

Share this post

Link to post
Share on other sites
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, 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.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!