/* Anders Brander <anders@brander.dk> 2001-03-08 */

/* Small util to get version information from a webserver */
#include <stdio.h>
#include <stdlib.h>

#if defined(WIN32)
#define _WIN32_
#endif
#ifndef _WIN32_
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#else
#include <winsock.h>
#endif

#include <errno.h>
#include <sys/types.h>
#include <string.h>

void bail(char *s);
char *which(char *);

int
main(int argc, char *argv[])
{

	if (argc!=2)
		bail("Too few arguments");

#ifdef _WIN32_
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD( 1, 1 ), &wsaData ))
		bail("WSAStartup() failed");
#endif

	printf("%s\n", which(argv[1]));

#ifdef _WIN32_
	if (WSACleanup())
		bail("WSACleanup() failed");
#endif
	return(0);
}

char *
which(char *host)
{
	struct sockaddr_in sa;
	struct hostent *hp;
	int a, s, inchar, n;
	char *tmp, *tmp2, *buff = malloc(8192);
	if ((hp = gethostbyname(host)) == NULL)
		return(NULL);

	memset(&sa,0,sizeof(sa));
	memcpy((char *)&sa.sin_addr,hp->h_addr,hp->h_length);
	sa.sin_family= hp->h_addrtype;
	sa.sin_port= htons((u_short)80);

	if ((s = socket(hp->h_addrtype,SOCK_STREAM,0)) < 0)
		return(NULL);
	if (connect(s,(struct sockaddr *)&sa,sizeof sa) < 0)
	{
#ifdef _WIN32_
		closesocket(s);
#else
		close(s);
#endif
		return(NULL);
	}
	send(s, "HEAD / HTTP/1.0\n\n", 17, 0);
	a = recv(s, buff, 8192, 0);
	buff[8191]='\0';
	tmp = (char *) strstr(buff, "\nServer: ");
	if (tmp==NULL)
		return(NULL);
	tmp +=9;
	tmp2 = (char *) strchr(tmp, '\n');
	if (tmp2==NULL) // You didn't think of THAT did you?
		return(NULL);
	tmp2[0] = '\0';
	tmp2 = malloc(strlen(tmp));
	strcpy(tmp2, tmp);
#ifdef _WIN32_
	closesocket(s);
#else
	close(s);
#endif

	return(tmp2);
}

void
bail(char *s)
{
	printf("%s\n", s);
	exit(1);
}

