// Copyright 1997-1998 Omni Development, Inc.  All rights reserved.

#import "ONPortAddress.h"

#import <Foundation/Foundation.h>
#import <OmniBase/OmniBase.h>
#import <OmniBase/system.h>

#import "ONHost.h"
#import "ONHostAddress.h"

RCS_ID("$Header: /Network/Developer/Source/CVS/OmniGroup/OmniNetworking/ONPortAddress.m,v 1.4 1998/01/12 06:53:49 kc Exp $")

@implementation ONPortAddress

- initWithHost:(ONHost *)aHost portNumber:(unsigned short int)port;
{
    NSArray *hostAddresses;

    hostAddresses = [aHost addresses];
    if ([hostAddresses count] == 0)
	[NSException raise:ONInternetSocketConnectFailedExceptionName
	 format:@"Unable to create port address: no IP address for host"];
    return [self initWithHostAddress:[hostAddresses objectAtIndex:0]
                          portNumber:port];
}

- initWithHostAddress:(ONHostAddress *)hostAddress portNumber:(unsigned short int)port;
{
    if (![super init])
        return nil;

    portAddress = (struct sockaddr_in *)NSZoneMalloc(NULL, sizeof(struct sockaddr_in));
    portAddress->sin_family = AF_INET;
    if (hostAddress)
	portAddress->sin_addr = *[hostAddress internetAddress];
    else
	portAddress->sin_addr.s_addr = htonl(INADDR_ANY);
    portAddress->sin_port = htons(port);

    return self;
}

- (void)dealloc;
{
    NSZoneFree(NULL, portAddress);
    [super dealloc];
}

- (const struct sockaddr_in *)portAddress;
{
    return portAddress;
}

- (const struct in_addr *)hostAddress;
{
    return &(portAddress->sin_addr);
}

- (unsigned long int)hostNumber;
{
    return ntohl(portAddress->sin_addr.s_addr);
}

- (unsigned short int)portNumber;
{
    return ntohs(portAddress->sin_port);
}

- (BOOL) isMulticastAddress;
{
    // Either inet_addr returns addresses in host byte order
    // or this macro expects them in host byte order.  It is
    // not clear from the documentation (such as it is).
    return IN_MULTICAST(ntohl(portAddress->sin_addr.s_addr));
}

@end
