Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014 #pragma once
00015
00019 #ifdef LINUX
00020 #include <sys/types.h>
00021 #include <sys/socket.h>
00022 #include <netinet/in.h>
00023 #endif
00024
00025 #include <cstring>
00026 #include <string>
00027
00028 namespace kNet
00029 {
00030
00032 struct EndPoint
00033 {
00035 unsigned char ip[4];
00036
00037 unsigned short port;
00038
00039 EndPoint()
00040 {
00041 Reset();
00042 }
00043
00045 void Reset()
00046 {
00047 memset(this, 0, sizeof(EndPoint));
00048 }
00049
00051 bool operator < (const EndPoint &rhs) const
00052 {
00053 if (ip[0] < rhs.ip[0]) return true;
00054 if (ip[0] > rhs.ip[0]) return false;
00055 if (ip[1] < rhs.ip[1]) return true;
00056 if (ip[1] > rhs.ip[1]) return false;
00057 if (ip[2] < rhs.ip[2]) return true;
00058 if (ip[2] > rhs.ip[2]) return false;
00059 if (ip[3] < rhs.ip[3]) return true;
00060 if (ip[3] > rhs.ip[3]) return false;
00061 if (port < rhs.port) return true;
00062 if (port > rhs.port) return false;
00063
00064 return false;
00065 }
00066
00068 static EndPoint FromSockAddrIn(const sockaddr_in &addr)
00069 {
00070 EndPoint endPoint;
00071 #ifdef WIN32
00072 endPoint.ip[0] = addr.sin_addr.S_un.S_un_b.s_b1;
00073 endPoint.ip[1] = addr.sin_addr.S_un.S_un_b.s_b2;
00074 endPoint.ip[2] = addr.sin_addr.S_un.S_un_b.s_b3;
00075 endPoint.ip[3] = addr.sin_addr.S_un.S_un_b.s_b4;
00076 #else
00077 endPoint.ip[0] = addr.sin_addr.s_addr & 0xFF;
00078 endPoint.ip[1] = (addr.sin_addr.s_addr >> 8) & 0xFF;
00079 endPoint.ip[2] = (addr.sin_addr.s_addr >> 16) & 0xFF;
00080 endPoint.ip[3] = (addr.sin_addr.s_addr >> 24) & 0xFF;
00081 #endif
00082 endPoint.port = ntohs(addr.sin_port);
00083
00084 return endPoint;
00085 }
00086
00088 sockaddr_in ToSockAddrIn() const
00089 {
00090 using namespace std;
00091
00092 sockaddr_in address;
00093 memset(&address, 0, sizeof(address));
00094 address.sin_family = AF_INET;
00095 address.sin_port = htons(port);
00096 #ifdef WIN32
00097 address.sin_addr.S_un.S_un_b.s_b1 = ip[0];
00098 address.sin_addr.S_un.S_un_b.s_b2 = ip[1];
00099 address.sin_addr.S_un.S_un_b.s_b3 = ip[2];
00100 address.sin_addr.S_un.S_un_b.s_b4 = ip[3];
00101 #else
00102 address.sin_addr.s_addr = ip[0] | (ip[1] << 8) | (ip[2] << 16) | (ip[3] << 24);
00103 #endif
00104
00105 return address;
00106 }
00107
00109 std::string IPToString() const
00110 {
00111 char str[256];
00112 sprintf(str, "%d.%d.%d.%d", (unsigned int)ip[0], (unsigned int)ip[1], (unsigned int)ip[2], (unsigned int)ip[3]);
00113 return std::string(str);
00114 }
00115
00117 std::string ToString() const
00118 {
00119 char str[256];
00120 sprintf(str, "%d.%d.%d.%d:%d", (unsigned int)ip[0], (unsigned int)ip[1], (unsigned int)ip[2], (unsigned int)ip[3], (unsigned int)port);
00121 return std::string(str);
00122 }
00123 };
00124
00125 }