jamescpp

Untitled

Nov 7th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.22 KB | None | 0 0
  1. #include <iostream>
  2.  
  3.  
  4. #include <arpa/inet.h>
  5. #include <netinet/in.h>
  6.  
  7. class ipAddress {
  8.  
  9.  
  10. public:
  11.     uint32_t m_address; //address in system byte order
  12.     ipAddress(uint32_t address):m_address(address){}
  13.  
  14.     ipAddress(std::string address, int af = AF_INET){
  15.         struct in_addr inAddr;
  16.         if(!inet_pton(af, address.c_str(), &inAddr)){
  17.             throw "Conversion of ip address to int failed";
  18.         }
  19.  
  20.         m_address = ntohl(inAddr.s_addr);
  21.     }
  22.  
  23.     ipAddress(const char* address, int af = AF_INET):
  24.         ipAddress((std::string) address, af){}
  25.  
  26.  
  27.  
  28.     operator std::string() const{
  29.         struct in_addr inAddr;
  30.         inAddr.s_addr = htonl(m_address);
  31.  
  32.         char tmp[256];
  33.         const char *ptr = inet_ntop(AF_INET, &inAddr, tmp, 256);
  34.         if(ptr == NULL){
  35.             throw "Conversion of int to ip address failed";
  36.         }
  37.  
  38.         return ptr; //this doesn't return ptr, it convert it to string automaticly end return string
  39.     }
  40.  
  41.     operator uint32_t() const{
  42.         return m_address;
  43.     }
  44.  
  45.     friend std::ostream& operator<<(std::ostream& os, const ipAddress& ipAddress);
  46. };
  47.  
  48. std::ostream& operator<<(std::ostream& os, const ipAddress& ipAddress){
  49.     os<<(std::string)ipAddress<<" [hex:"<<std::hex<<(uint32_t)ipAddress<<std::dec<<"] ";
  50.     return os;
  51. }
  52.  
  53. uint32_t func(uint32_t cislo){ return cislo; }
  54.  
  55. int main(){
  56.     ipAddress remote = "192.168.0.5";
  57.     ipAddress local = "127.0.0.1";
  58.     ipAddress zCisla = 0xf0f0f0f0;
  59.  
  60.     std::cout<<"Remote "<< remote <<std::endl;
  61.     std::cout<<"Local "<< local <<std::endl;
  62.     std::cout<<"FromNumber "<< zCisla <<std::endl;
  63.  
  64.     std::string remoteAddressString = remote;
  65.  
  66.     std::cout<<"Remote S:"<< remoteAddressString <<std::endl;
  67.     std::cout<<"Local S:"<< (std::string)local <<std::endl;
  68.     std::cout<<"FromNumber S:"<< (std::string)zCisla <<std::endl;
  69.  
  70.  
  71.     uint32_t remoteAddressInteger = remote;
  72.  
  73.     std::cout<<"Remote I:"<< remoteAddressInteger <<std::endl;
  74.     std::cout<<"Local I:"<< func(local) <<std::endl; //ked to davas niekam kde kompiler vie ze to ma byt int alebo string tak to nemusis pisat spravi sa to samo
  75.     std::cout<<"FromNumber I:"<< (uint32_t)zCisla <<std::endl;
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment