views:

876

answers:

2

Ping is not working. Telnet is not an option, sending a mail also. Preferably a function from a library that returns true or false.

Thanks.

+1  A: 

If by working you mean open, you can just connect to the port and see if the socket opens successfully.

If you mean that it's accepting valid SMTP over SSL, then you'd need a library that connects and issues a trivial SMTP command like HELO or something.

Chilkat has library code and examples for this.

Example connect code for win32:

#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h>

void tryconnect(const char * host, const char * port)
{
    SOCKET Socket = INVALID_SOCKET;
    struct addrinfo *resAddrInfo = NULL;
    struct addrinfo *ptr = NULL;
    struct addrinfo hints;
    int result = 0;

    printf("Connecting to %s:%s\n", host, port);

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    result = getaddrinfo(host, port, &hints, &resAddrInfo);
    if (result != 0)
    {
     printError("getaddrinfo failed");
     return;
    }

    ptr = resAddrInfo;
    Socket = WSASocket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol, NULL, 0, WSA_FLAG_OVERLAPPED);
    if (Socket == INVALID_SOCKET)
    {
     printError("Error Creating Socket");
     freeaddrinfo(resAddrInfo);
     return;
    }

    result = WSAConnect(Socket, ptr->ai_addr, (int)ptr->ai_addrlen, NULL, NULL, NULL, NULL);
    if (result != 0)
    {
     printError("Error Connecting");
     closesocket(Socket);
     freeaddrinfo(resAddrInfo);
     return;
    }

    freeaddrinfo(resAddrInfo);
    printf("Success!\n\n");
}
John Weldon
When a try connect to the server by ping all I get is a timeout, but the server is working.
Thanks, but Chilkat is 20 Meg library, a bit of an overkill :)
If you're just trying to replicate ping, then open a socket to that port and see if it connects.
John Weldon
John, what headers are you using for this function winsock, ws2tcpip ??
Added includes to the sample code
John Weldon
also, use the Ws2_32.lib library too
John Weldon
Yes I had to add #pragma comment(lib,"ws2_32.lib") : )
The function fails at "getaddrinfo failed". Is it possible that the server is refusing connection without authentication ?
I'll try to digg in this direction. Thanks for the code.
Hmm; getaddrinfo is just essentially a DNS lookup. Something else is wrong.
John Weldon
I checked the error of getaddrinfo and I got 10093 WSANOTINITIALISED10093. So I added WSADATA data;WSAStartup(MAKEWORD(2, 2), And now Everything is Working ! Thanks.
+1  A: 

Just make an SSL connection to the SMTP server and attempt to read a line from the stream. The server should send a greeting message as soon as you establish a connection like "220 smtp.domain.com"

Gerald
Don't forget to connect over an SSL link if you do this..:)
John Weldon
Figured that was a given, but updated my answer for clarity.
Gerald