Search code examples
iosmacossocketssecure-transport

How can I cast a socket to an SSLConnectionRef without getting a warning?


I'm learning how to use Apple's Secure Transport framework to implement TLS for my networking, and it's a bit confusing. I believe I'm supposed to just cast my socket fds to SSLConnectionRefs, but I get a warning when I do so Cast to 'SSLConnectionRef' (aka 'const void *') from smaller integer type 'int'.

int sockfd = socket(...);
...
SSLContextRef sslContext = SSLCreateContext(...);

// This line gives the warning
SSLSetConnection(sslContext, (SSLConnectionRef)sockfd);

I'm not losing any information here, since void * is larger than int, right? So this should be safe. I'm just concerned by the compiler warning. Thanks for any suggestions.


Solution

  • (SSLConnectionRef)(long)sockfd works and should be safe as long as sizeof(void*) > sizeof(int) which is true for all current compilers, but not necessarily guaranteed.

    Another approach would be to temporarily disable the warning:

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wint-to-point-cast"
        SSLSetConnection(sslContext, (SSLConnectionRef)sockfd);
    #pragma clang diagnostic pop
    

    Ultimately, the "right" solution would be to actually pass in a pointer to an integer that you allocate via malloc or some other scheme. If this is all in an object, store the fd in an instance variable and pass in &_sockfd;