/*
 * @(#)Socket.cpp
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 *
 * Jörg Haeger, 19.04.2002
 */

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include "BufferedReader.h"
#include "Support.h"
#include "Socket.h"

Socket::Socket(int fd) {
	this->fd = fd;
	inputStream = new BufferedReader(fd);
}

Socket::~Socket() {
	if (inputStream != NULL)
		delete inputStream;
	close(fd);
}

const char *Socket::getInetAddress() {
	struct sockaddr_in name;
	socklen_t len = sizeof name;
	if (getpeername(fd, (struct sockaddr *)&name, &len) == 0) {
		char str[256];
		if (inet_ntop(name.sin_family, &name.sin_addr,
			str, sizeof str) != NULL)
			return strdup(str);
	}

	return NULL;
}

BufferedReader &Socket::getInputStream() {
	return *inputStream;
}

int Socket::getOutputStream() {
	return fd;
}

int Socket::getPort() {
	struct sockaddr_in name;
	socklen_t len = sizeof name;
	if (getpeername(fd, (struct sockaddr *)&name, &len) == 0)
		return name.sin_port;

	return 0;
}
