资源描述:
《网络地址封装类》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Netaddr.h#ifndef__NET_ADDR_H#define__NET_ADDR_H#includeusingstd::ostream;//功能:网络地址封装#includeclassCNF_Net_Addr{public:CNF_Net_Addr();CNF_Net_Addr(conststructsockaddr_in&addr);CNF_Net_Addr(unsignedshortport,constchar*ip=NULL,boolport_isRaw=true);boo
2、loperator==(constCNF_Net_Addr&other)const;intset(conststructsockaddr_in&addr);intset_ip(constchar*ip=NULL);//xxx.xxx.xxx.xxxintset_port(unsignedshortport,boolisRaw=true);voidget_port(unsignedshort&port)const;voidget_ip(charip[16])const;operatorstructsockaddr_in()const;p
3、rivate:structsockaddr_insockaddr;};ostream&operator<<(ostream&s,constCNF_Net_Addr&addr);classCNF_Net_Addr_Pair{public:CNF_Net_Addr_Pair(unsignedshortpeer_port,constchar*peer_ip,unsignedshortlocal_port,constchar*local_ip){peer.set_port(peer_port);peer.set_ip(peer_ip);loc
4、al.set_port(local_port);local.set_ip(local_ip);}public:CNF_Net_Addrpeer;CNF_Net_Addrlocal;};#endifNetaddr.cpp#include"Net_Addr.h"#include#include#include#include#includeCNF_Net_Addr::CNF_Net_Addr(){memset(&sock
5、addr,0,sizeof(sockaddr));sockaddr.sin_family=PF_INET;}CNF_Net_Addr::CNF_Net_Addr(conststructsockaddr_in&addr_):sockaddr(addr_){}CNF_Net_Addr::CNF_Net_Addr(unsignedshortport,constchar*ip,boolport_isRaw){memset(&sockaddr,0,sizeof(sockaddr));sockaddr.sin_family=PF_INET;set
6、_ip(ip);set_port(port,port_isRaw);}intCNF_Net_Addr::set(conststructsockaddr_in&addr){sockaddr=addr;return0;}intCNF_Net_Addr::set_ip(constchar*ip){if(ip){return0==inet_aton(ip,&sockaddr.sin_addr)?-1:0;}else{sockaddr.sin_addr.s_addr=htonl(INADDR_ANY);return0;}}intCNF_Net_
7、Addr::set_port(unsignedshortport,boolisRaw){if(isRaw){sockaddr.sin_port=htons(port);}else{sockaddr.sin_port=port;}return0;}voidCNF_Net_Addr::get_port(unsignedshort&port)const{port=ntohs(sockaddr.sin_port);}voidCNF_Net_Addr::get_ip(charaddr[16])const{snprintf(addr,16,ine
8、t_ntoa(sockaddr.sin_addr));}CNF_Net_Addr::operatorstructsockaddr_in()const{returnsockaddr;}boolCNF_Net_Addr::o