// ---------------------------- FCNTP.h ---------------------------------------
#if defined _WIN32
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/param.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include <string.h>
#include <exception>
class FCNTP_EXCP : public exception // 例外クラス
{
public:
FCNTP_EXCP() throw () {m_strData = "Unknown Exception"; }
FCNTP_EXCP(const char *strException) throw (){m_strData = strException; }
const char *what() throw() { return m_strData; }
private:
const char *m_strData;
};
class FCNTP {
public:
FCNTP();
~FCNTP();
int socket(void) throw (FCNTP_EXCP);
int connect(const char *strServerIP) throw (FCNTP_EXCP);
int recv(unsigned long *pulTime) throw (FCNTP_EXCP);
int close(void);
int _s;
};
//---------------------------- FCNTP.cpp --------------------------------------
#include "FCNTP.h"
FCNTP::FCNTP()
{
_s = -1;
}
FCNTP::~FCNTP()
{
close();
}
int FCNTP::socket() throw (FCNTP_EXCP)
{
_s = ::socket(AF_INET, SOCK_STREAM, 0);
if (_s == -1) {
throw FCNTP_EXCP("使えねーじゃん");
}
return 0;
}
int FCNTP::connect(const char *strServerIP) throw (FCNTP_EXCP)
{
unsigned long ulAddr;
unsigned short usPort;
sockaddr sa;
memset(&sa, 0, sizeof(sa));
sa.sa_family = AF_INET;
usPort = htons(37); // ポート番号をネットワークバイトオーダーに変換
ulAddr = inet_addr(strServerIP);
memmove(sa.sa_data, &usPort, 2);
memmove(sa.sa_data + 2, &ulAddr, 4);
if (::connect(_s, &sa, sizeof(sa)) == -1) {
throw FCNTP_EXCP("繋がんねーじゃん(Д");
}
return 0;
}
int FCNTP::recv(unsigned long *pulTime) throw (FCNTP_EXCP)
{
unsigned long ulRVal = 0L;
if (::recv(_s, reinterpret_cast<char *>(&ulRVal), 4, 0) == -1) {
throw FCNTP_EXCP("受信できねーぞ(Д");
}
*pulTime = ntohl(ulRVal); // 返り値をネットワークバイトオーダーから変換
return 0;
}
int FCNTP::close()
{
#if defined _WIN32
::shutdown(_s, SD_BOTH);
::closesocket(_s);
#else
::shutdown(_s, SHUT_RDWR);
::close(_s);
#endif
return 0;
}
|