Search code examples
objective-cios6reachability

ReachabilityCreateWithAddress struct in_addr, ip-format


I'm want to write an ip-check with the reachability.h and reachability.m from apples sample code.

I want to use this function:

+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) ipAddress;

So it gets an sockaddr_in structure.

I get so far:

struct sockaddr_in ipAddress;
    ipAddress.sin_len = sizeof(ipAddress);
    ipAddress.sin_family = AF_INET;
    ipAddress.sin_port = 80;
    struct  in_addr sin_addr = ???; //???
    char        sin_zero[8];

The ip address is a struct, too.

struct in_addr {
    in_addr_t s_addr;
};


typedef __uint32_t      in_addr_t;  /* base type for internet address */

But how I can put an ip address in the struct? Which format i got to use? E.g. 192.168.2.2 doesn't work.

Thanks ahead.


Solution

  • You can use inet_pton() (defined in <arpa/inet.h>) to convert a string containing a network address to network format. And note that you have to convert the port number from host byte order to network byte order:

    struct sockaddr_in ipAddress;
    ipAddress.sin_len = sizeof(ipAddress);
    ipAddress.sin_family = AF_INET;
    ipAddress.sin_port = htons(80);
    inet_pton(AF_INET, "192.168.2.2", &ipAddress.sin_addr);