Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- class ipAddress {
- public:
- uint32_t m_address; //address in system byte order
- ipAddress(uint32_t address):m_address(address){}
- ipAddress(std::string address, int af = AF_INET){
- struct in_addr inAddr;
- if(!inet_pton(af, address.c_str(), &inAddr)){
- throw "Conversion of ip address to int failed";
- }
- m_address = ntohl(inAddr.s_addr);
- }
- ipAddress(const char* address, int af = AF_INET):
- ipAddress((std::string) address, af){}
- operator std::string() const{
- struct in_addr inAddr;
- inAddr.s_addr = htonl(m_address);
- char tmp[256];
- const char *ptr = inet_ntop(AF_INET, &inAddr, tmp, 256);
- if(ptr == NULL){
- throw "Conversion of int to ip address failed";
- }
- return ptr; //this doesn't return ptr, it convert it to string automaticly end return string
- }
- operator uint32_t() const{
- return m_address;
- }
- friend std::ostream& operator<<(std::ostream& os, const ipAddress& ipAddress);
- };
- std::ostream& operator<<(std::ostream& os, const ipAddress& ipAddress){
- os<<(std::string)ipAddress<<" [hex:"<<std::hex<<(uint32_t)ipAddress<<std::dec<<"] ";
- return os;
- }
- uint32_t func(uint32_t cislo){ return cislo; }
- int main(){
- ipAddress remote = "192.168.0.5";
- ipAddress local = "127.0.0.1";
- ipAddress zCisla = 0xf0f0f0f0;
- std::cout<<"Remote "<< remote <<std::endl;
- std::cout<<"Local "<< local <<std::endl;
- std::cout<<"FromNumber "<< zCisla <<std::endl;
- std::string remoteAddressString = remote;
- std::cout<<"Remote S:"<< remoteAddressString <<std::endl;
- std::cout<<"Local S:"<< (std::string)local <<std::endl;
- std::cout<<"FromNumber S:"<< (std::string)zCisla <<std::endl;
- uint32_t remoteAddressInteger = remote;
- std::cout<<"Remote I:"<< remoteAddressInteger <<std::endl;
- 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
- std::cout<<"FromNumber I:"<< (uint32_t)zCisla <<std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment