如何使用D将IP地址转换为字节数组?

时间:2016-08-17 07:07:25

标签: ip d

我正在查看std.socket,我能够执行以下操作来检查IP类型,但我找不到获取IP地址字节数组的方法。

auto results = getAddressInfo(ipaddress, AddressInfoFlags.NUMERICHOST);

if (results.length && results[0].family == AddressFamily.INET) {
    writeln("IPv4 : " ~ results[0].address.toAddrString());
    return 4;
}
else if (results.length && results[0].family == AddressFamily.INET6) {
    writeln("IPv6 : " ~ results[0].address.toAddrString());
    return 6;
}

我看到了一些像InternetAddress和Internet6Address这样的类,它们具有返回字节数组的addr()属性,但我不知道如何从上面的代码转到这两个类。

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是使用Address.name获取指向core.sys.posix.sys.socket.sockaddr结构的指针。 像auto saddr_ptr = results[0].address.name;这样的东西会做。然后,您可以通过将此指针强制转换为适当类型的指针(取决于地址族)来提取所需的数据。

以下是来自getAddress()文档的修改示例,该文档使用sockaddr *将地址作为uint32_t值并将它们转换为ubyte [4]数组:

module main;

import std.stdio;
import std.socket;
import std.c.linux.socket: sockaddr_in, in_addr;

void main(string[] args) {
    // auto results = getAddressInfo("www.digitalmars.com");

    try {
        Address[] addresses = getAddress("dlang.org", 80);
        writefln("  %d addresses found.", addresses.length);
        foreach (int i, Address a; addresses) {

            writefln("  Address %d:", i+1);
            writefln("    IP address: %s", a.toAddrString());
            writefln("    Hostname: %s", a.toHostNameString());
            writefln("    Port: %s", a.toPortString());
            writefln("    Service name: %s", a.toServiceNameString());
            auto saddr_ptr = a.name;
            auto in_ptr = *(cast(sockaddr_in*) saddr_ptr);
            // let's convert it to ubyte[4] so we can access individual
            // parts  of the IPv4 address.
            writeln(cast(ubyte[4])(in_ptr.sin_addr));
        }
    } catch (SocketException e) {
        writefln("  Lookup error: %s", e.msg);
    }

    // Lets the user press <Return> before program returns
    stdin.readln();
}

输出:

  3 addresses found.
  Address 1:
    IP address: 162.217.114.56
    Hostname: digitalmars.com
    Port: 80
    Service name: http
[162, 217, 114, 56]
  Address 2:
    IP address: 162.217.114.56
    Hostname: digitalmars.com
    Port: 80
    Service name: http
[162, 217, 114, 56]
  Address 3:
    IP address: 162.217.114.56
    Hostname: digitalmars.com
    Port: 80
    Service name: http
[162, 217, 114, 56]