www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to test that the IP port is reachable?

reply FrankLike <1150015857 qq.com> writes:
Hi,everyone,

How to test that the IP port is reachable?

In C,you can do this like that, what should I do in D?

/* C Code*/
https://blog.csdn.net/zhangyingchuang/article/details/51957552

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>    /* inet(3) functions */

#define bool int
#define false 0
#define true 1

bool checkIPandPort(const char* ip, const char* port) {
    struct sockaddr_in addr;
    int fd = socket(AF_INET, SOCK_STREAM, 0);

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);

    if (connect(fd, (struct sockaddr *) &addr, sizeof(struct 
sockaddr)) < 0) {
        printf("connect error \n");
        return false;
    }
    return true;
}
----------------------------------------------------------
But how to do it in D?
Thanks.
Apr 05 2019
parent FrankLike <1150015857 qq.com> writes:
On Saturday, 6 April 2019 at 03:24:04 UTC, FrankLike wrote:
 Hi,everyone,...
Do you have some better code than this? ---------------------------------------------------------------- import std.stdio; import std.socket; void main() { testIPPort(); } bool testIPPort() { try { auto results = getAddressInfo("127.0.0.1",AddressInfoFlags.NUMERICHOST); auto sock = new Socket(results[0]); auto address = getAddress("127.0.0.1",8080); sock.connect(address[0]); writeln(address," connect ok"); return true; } catch(SocketException e) { return false; } } --------------------------------------- Thanks.
Apr 05 2019