OTWO-1213 Works around lost encoding in Ruby/C binding layer
[ohcount] / test / detect_files / TCPSocket.m
1 /** 
2  * This code is free software; you can redistribute it and/or modify it under
3  * the terms of the new BSD License.
4  *
5  * Copyright (c) 2009, Sebastian Staudt
6  */
7
8 #import <arpa/inet.h>
9 #import <netinet/in.h>
10
11 #import "SteamCondenserException.h"
12 #import "TCPSocket.h"
13
14
15 @implementation TCPSocket
16
17 -(void) connectWithHost:(NSHost*) aHost andPort:(unsigned short) aPort {
18     remoteHost = aHost;
19     remotePort = aPort;
20     
21     struct sockaddr_in remoteSocket;
22     remoteSocket.sin_family = AF_INET;
23     remoteSocket.sin_port = htons(remotePort);
24     NSString* address;
25     NSEnumerator* addressEnumerator = [[remoteHost addresses] objectEnumerator];
26     while(address = [addressEnumerator nextObject]) {
27         if(inet_pton(AF_INET, [address cStringUsingEncoding:NSASCIIStringEncoding], &remoteSocket.sin_addr) == 1) {
28             break;
29         }
30     }
31     
32     fdsocket = socket(AF_INET, SOCK_STREAM, 0);
33     if(fdsocket < 0) {
34         @throw [[SteamCondenserException alloc] initWithMessage:[NSString stringWithFormat:@"Error creating socket: %s", strerror(errno)]];
35     }
36     
37     if(connect(fdsocket, (struct sockaddr*) &remoteSocket, sizeof(remoteSocket)) < 0) {
38         @throw [[SteamCondenserException alloc] initWithMessage:[NSString stringWithFormat:@"Error connecting socket: %s", strerror(errno)]];
39     }
40     
41     if(!isBlocking) {
42         fcntl(fdsocket, F_SETFL, O_NONBLOCK);
43     }
44     else {
45         fcntl(fdsocket, F_SETFL, 0);
46     }
47 }
48
49 @end