I'm using Apple's TCPServer class to open a socket on listen from incoming connection. Here is the callback that get called when someone connect on the listening socket:
static void TCPServerAcceptCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) {
TCPServer *server = (TCPServer *)info;
if (kCFSocketAcceptCallBack == type) {
// for an AcceptCallBack, the data parameter is a pointer to a CFSocketNativeHandle
CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data;
uint8_t name[SOCK_MAXADDRLEN];
socklen_t namelen = sizeof(name);
NSData *peer = nil;
if (0 == getpeername(nativeSocketHandle, (struct sockaddr *)name, &namelen)) {
peer = [NSData dataWithBytes:name length:namelen];
}
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream);
if (readStream && writeStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
[server handleNewConnectionFromAddress:peer inputStream:(NSInputStream *)readStream outputStream:(NSOutputStream *)writeStream];
} else {
// on any failure, need to destroy the CFSocketNativeHandle
// since we are not going to use it any more
close(nativeSocketHandle);
}
if (readStream) CFRelease(readStream);
if (writeStream) CFRelease(writeStream);
}
}
Is there any way to get the hostname of the device which is connecting ? Regards, Kosa
[EDIT] I tried something like this to extract the ip:
struct sockaddr_in *s = (struct sockaddr_in*)name;
char *ipstr = malloc(INET_ADDRSTRLEN);
ipstr = inet_ntoa(s->sin_addr);
NSLog(@"ip = %s", ipstr);
But it gives me 0.0.0.0.
[EDIT] Still working on it and still no success. According to apple's doc the address parameter is:
A CFData object holding the contents of a struct sockaddr appropriate for the protocol family of s (struct sockaddr_in or struct sockaddr_in6, for example), identifying the remote address to which s is connected. This value is NULL except for kCFSocketAcceptCallBack and kCFSocketDataCallBack callbacks.
However I can't extract any other IP than 132.20.0.1 (which is obviously not the IP I'm expecting) I'm really confused and it would be great if someone could help me with that !