4

Reachabilitty我在 Swift 中玩 Apple 的课程。

我的私人 Wi-Fi 中的网络服务器在http://10.0.0.1. 为了检查它的可达性,我想使用以下函数Reachability.h(不是带有主机名的函数):

/*!
 * Use to check the reachability of a given IP address.
 */
+ (instancetype)reachabilityWithAddress:(const struct sockaddr *)hostAddress;

sockaddr看起来socket.h像这样:

/*
 * [XSI] Structure used by kernel to store most addresses.
 */
struct sockaddr {
    __uint8_t   sa_len;     /* total length */
    sa_family_t sa_family;  /* [XSI] address family */
    char        sa_data[14];    /* [XSI] addr value (actually larger) */
};

如何在 Swift 中创建sockaddr具有 ip 地址的结构?10.0.0.1

我已经读过 [这里] 一些关于UnsafePointerand的内容,UnsafeMutablePointer并且 C 数组(或者在这种情况下是一个 Objective-C 数组?)在 Swift 中表示为元组,但我仍然不确定如何使用它们。

4

1 回答 1

9

您创建了sockaddr_in第一个:

var addr = sockaddr_in()
addr.sin_len = UInt8(MemoryLayout.size(ofValue: addr))
addr.sin_family = sa_family_t(AF_INET)

addr.sin_addr.s_addr = inet_addr("10.0.0.1")
// Alternatively:
inet_pton(AF_INET, "10.0.0.1", &addr.sin_addr)

然后将其“重新绑定”到一个sockaddr指针,例如

let reachability = withUnsafePointer(to: &addr, {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
        SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, $0)
    }
})

一些解释:

There are different address types for different address families (such as struct sockaddr_in for IPv4, struct sockaddr_in6 for IPv6). struct sockaddr is the “common part”, and many socket functions which take a pointer to a sockaddr as parameter.

In C you can simply cast between the pointers:

struct sockaddr sin;
// ...
struct sockaddr *addrPtr = (struct sockaddr *)&sin;

In Swift that is done more explicitly as “rebinding”. For more information, see

于 2018-03-23T18:45:35.363 回答