first sockets prog

Started by
6 comments, last by temp_ie_cant_thinkof_name 19 years, 11 months ago
Here''s some simple code from a sockets tutorial:

#pragma comment(lib, "wsock32.lib")

#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>

#define RCVBUFSIZE 32

void die_with_error(char *error_message);

void main(int argc, char *argv[])
{
	int sock;
	struct sockaddr_in echo_serv_addr;
	unsigned short echo_serv_port;
	char *serv_ip;
	char *echo_string;
	char echo_buffer[RCVBUFSIZE];
	int echo_string_len;
	int bytes_rcvd, total_bytes_rcvd;
	WSADATA wsa_data;

	if ((argc < 3) || (argc > 4))
	{
		fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n",
			argv[0]);
		exit(1);
	}

	serv_ip = argv[1];
	echo_string = argv[2];

	if (argc == 4)
		echo_serv_port = atoi(argv[3]);
	else
		echo_serv_port = 7;

	if (WSAStartup(MAKEWORD(2, 0), &wsa_data) != 0)
	{
		fprintf(stderr, "WSAStartup() failed");
		exit(1);
	}

	if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
		die_with_error("socket() failed");

	memset(&echo_serv_addr, 0, sizeof(echo_serv_addr));
	echo_serv_addr.sin_family		= AF_INET;
	echo_serv_addr.sin_addr.s_addr	= inet_addr(serv_ip);
	echo_serv_addr.sin_port = htons(echo_serv_port);
	
	if (connect(sock, (struct sockaddr *) &echo_serv_addr, sizeof(echo_serv_addr)) < 0)
		die_with_error("connect() failed");
	
	echo_string_len = strlen(echo_string);

	if(send(sock, echo_string, echo_string_len, 0) != echo_string_len)
		die_with_error("send() sent a different number of bytes than expected");

	total_bytes_rcvd = 0;
	printf("Received: ");

	while (total_bytes_rcvd < echo_string_len)
	{
		if((bytes_rcvd = recv(sock, echo_buffer, RCVBUFSIZE -1, 0)) <= 0)
			die_with_error("recv90 failed or connection closed prematurely");
		total_bytes_rcvd += bytes_rcvd;
		echo_buffer[bytes_rcvd] = ''\0'';
		printf(echo_buffer);
	}

	printf("\n");
	closesocket(sock);
	WSACleanup();

	exit(0);
}

void die_with_error(char *error_message)
{
	fprintf(stderr, "%s: %d\n", error_message, WSAGetLastError());
	exit(1);
}
I can TRY connecting to local host on any port, but one cannot connect because there''s no echo server listening on any port, right? So how does a begginer see how their prog works--do they have to make a server to listen for a connection?
"I study differential and integral calculus in my spare time." -- Karl Marx
Advertisement
Basically, yes. Most beginning sockets programming tutorials for client programs usually come with a corresponding server program for testing purposes.

Some people run alternate boxes on their LANs with linux boxen, etc. but that may not be an option for you.
Ayup.

1) Write your own
2) Run an echo server.

You can find some examples of Python and Perl Echo servers that are about 10 lines long if you''re impatient and want to get started now.

A quick google search for "Python echo server" will return a lot of quick scripts you can use to test your code with.

Int.



One more question: I googled for an echo server example as simple as the code I posted to no avail. So i''ll try making my own simple one. Will I have any problems with a server and client listening and connecting on the same port on my single machine? I''m running windows xp.
"I study differential and integral calculus in my spare time." -- Karl Marx
Running the server and the client on the same machine should pose no problems unless you are doing something horribly wrong.
The server listens on a port. This port then becomes allocated to that process.

The client then connects to that port on the server (which happens to be the same machine). The TCP protocol then allocates a random, un-used port number to use for the client side of the connection.

Thus, yes, it''s quite possible to have a server listening on a port, and then connect to that server from a client on the same machine.

enum Bool { True, False, FileNotFound };
Kthx, everyone, for your quick replies.
"I study differential and integral calculus in my spare time." -- Karl Marx
From a google search:


#! /usr/bin/env python

# Simple Python implementation of an ''echo'' tcp server:
# echo all data it receives.
#
# This is the simplest possible server, servicing a single request only.

import socket

portnr=9000
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind('''', 9000)
s.listen(1)
conn, addr = s.accept()
print conn.getsockname()
print conn.getpeername()
data=conn.recv(128)
print data

This topic is closed to new replies.

Advertisement