//
//  ALSocketPort.m
//  Aluminum Framework
//
//  Created by Philippe Hausler on 8/8/08.
//  Copyright 2008. All rights reserved.
//


#import "TCPSocket.h"
@implementation TCPSocket
- (id)initWithTCPPort:(unsigned short)port
{
	self = [super init];
	if ( (fd = socket( AF_INET, SOCK_STREAM, 0 )) < 0 ) {
		return NULL;
	}
	int on = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
	bzero( &serverAddress, sizeof(serverAddress) );
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_port = htons(port);
	serverAddress.sin_addr.s_addr = htonl( INADDR_ANY );
	
	if ( bind( fd, (struct sockaddr *)&serverAddress, sizeof(serverAddress) ) < 0 ) {
		return NULL;
	}
	
	if ( listen( fd, 5 ) < 0 ) {
		return NULL;
	}
	return self;
}
- (id)initWithConnectionTo:(NSString *)host onTCPPort:(unsigned short)port
{
	self = [super init];
	fd = socket(PF_INET, SOCK_STREAM, 0);
	
    if(fd == -1)
    {
		return NULL;
    }
	
    struct sockaddr_in stSockAddr;
    bzero(&stSockAddr, sizeof(stSockAddr));
	
    stSockAddr.sin_family = AF_INET;
    stSockAddr.sin_port = htons(port);
	
	struct hostent *host_entry = gethostbyname([host UTF8String]);
	char * ip = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
	
    int err = inet_pton(AF_INET, ip, (void *) &stSockAddr.sin_addr);
	
    if(err <= 0)
    {
		return NULL;
    }
	
    if(connect(fd,(struct sockaddr*) &stSockAddr, sizeof(stSockAddr)) == -1)
    {
		return NULL;
    }
	return self;
}
- (NSData *)address
{
	return [NSData dataWithBytes:(void *)&serverAddress length:sizeof(struct sockaddr_in)];
}
- (NSSocketNativeHandle)socket
{
	return fd;
}
@end
