3 * Copyright (c) 2002 - 2007, Blue Static <http://www.bluestatic.org>
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17 #import "SocketWrapper.h"
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
23 @implementation SocketWrapper
26 * Initializes the socket wrapper with a host and port
28 - (id)initWithPort
: (int)port
30 if (self = [super init
])
32 // create an INET socket that we'll be listen()ing on
33 int socketOpen
= socket(PF_INET
, SOCK_STREAM
, 0);
35 // create our address given the port
36 struct sockaddr_in address
;
37 address.sin_family
= AF_INET
;
38 address.sin_port
= htons(port
);
39 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
40 memset(address.sin_zero
, '\0', sizeof(address.sin_zero
));
42 // bind the socket... and don't give up until we've tried for a while
44 while (bind(socketOpen
, (struct sockaddr
*)&address
, sizeof(address
)) < 0)
49 NSLog(@
"giving up now");
52 NSLog(@
"couldn't bind to the socket... trying again in 5");
57 // now we just have to keep our ears open
58 if (listen(socketOpen
, 0) == -1)
60 NSLog(@
"listen failed");
64 // accept a connection
65 struct sockaddr_in remoteAddress
;
66 socklen_t remoteAddressLen
= sizeof(remoteAddress
);
67 _socket
= accept(socketOpen
, (struct sockaddr
*)&remoteAddress
, &remoteAddressLen
);
71 NSLog(@
"could not accept() the socket");
75 // we're done listening now that we have a connection
82 * Close our socket and clean up anything else