本文整理汇总了C++中Address::getPort方法的典型用法代码示例。如果您正苦于以下问题:C++ Address::getPort方法的具体用法?C++ Address::getPort怎么用?C++ Address::getPort使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Address
的用法示例。
在下文中一共展示了Address::getPort方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: operator
bool addressComparator::operator ()(const Address &lhs, const Address &rhs) const {
int i = lhs.getHost().compare(rhs.getHost());
if (i == 0) {
return lhs.getPort() > rhs.getPort();
}
return i > 0;
}
示例2: receive
int NetworkedClient::receive(int timeout){
char buf[NETWORKED_MODULE_RECEIVE_BUFFER_SIZE];
Address remote;
int size=socket.recvFrom(remote, buf, NETWORKED_MODULE_RECEIVE_BUFFER_SIZE, timeout);
// std::cout << __PRETTY_FUNCTION__ << "begin" << std::endl;
if (remote.getHost()==0xffffffff){
// std::cout << __PRETTY_FUNCTION__ << " broadcast HOST" << std::endl;
elapsedTimeoutReceived();
return 0;
} else {
PeerInfoMap::iterator peer=peers.find(remote);
if (peer==peers.end()){
PeerInfo pinfo;
peers.insert(std::make_pair(remote,pinfo));
peer=peers.find(remote);
std::cout << "registering supplier HOST= " <<remote.getHost() << " port=" << remote.getPort() <<std::endl;
}
gettimeofday(&peer->second.lastPingTime, 0);
socket.sendTo(remote,"",0);
// std::cout << "Parsing" << std::endl;
if (size)
parseMessage(size, buf);
return size;
}
}
示例3: packAddress
QByteArray Common::packAddress(const Address &addr)//pack a shadowsocks header
{
QByteArray ss_header;
QByteArray address_str = addr.getAddress().toLocal8Bit();
QByteArray address_bin;
quint16 port_net = htons(addr.getPort());
QByteArray port_ns = QByteArray::fromRawData(reinterpret_cast<char *>(&port_net), 2);
int type = addr.addressType();
ss_header.append(static_cast<char>(type));
switch (type) {
case Address::ADDRTYPE_HOST://should we care if it exceeds 255?
ss_header.append(static_cast<char>(address_str.length()));
ss_header += address_str;
break;
case Address::ADDRTYPE_IPV4:
address_bin.resize(INET_ADDRSTRLEN);
inet_pton(AF_INET, address_str.constData(), reinterpret_cast<void *>(address_bin.data()));
ss_header += address_bin;
break;
case Address::ADDRTYPE_IPV6:
address_bin.resize(INET6_ADDRSTRLEN);
inet_pton(AF_INET6, address_str.constData(), reinterpret_cast<void *>(address_bin.data()));
ss_header += address_bin;
break;
}
return ss_header + port_ns;
}
示例4: resolve
Address Resolver::resolve(const Address &cInfo)
{
string addrOut;
const char *addr=cInfo.getHost().c_str();
if( strcmp(addr, "*")==0 ) // all addresses?
addrOut="0.0.0.0"; // addr-any
else
{
if( inet_addr(addr)==INADDR_NONE ) // non-IP?
{
// if everyting fails - try DNS:
struct hostent *dns_info=gethostbyname(addr);
if(dns_info==NULL || dns_info->h_addr_list[0]==NULL) // no match?
throw Exception("Resolver::resolve(): unknown host '" +
cInfo.getHost() + "'");
// choose first from the list...
const in_addr *inAddr=reinterpret_cast<in_addr*>(
dns_info->h_addr_list[0]);
const char *tab =inet_ntoa(*inAddr);
addrOut=string(tab);
}
else // if(non-IP)
{
// so this is a correct address!
addrOut=cInfo.getHost();
};
}; // else(addr=="*")
// returned resolved host info
Address resolved(addrOut, cInfo.getPort() );
return resolved;
};
示例5: onClientUdpSocketReadyRead
void UdpRelay::onClientUdpSocketReadyRead()
{
QUdpSocket *sock = qobject_cast<QUdpSocket *>(sender());
if (!sock) {
emit info("Fatal. A false object calling onClientUdpSocketReadyRead.");
return;
}
if (sock->pendingDatagramSize() > RecvSize) {
emit info("[UDP] Datagram is too large. Discarded.");
return;
}
QByteArray data;
data.resize(sock->pendingDatagramSize());
QHostAddress r_addr;
quint16 r_port;
sock->readDatagram(data.data(), RecvSize, &r_addr, &r_port);
QByteArray response;
if (isLocal) {
data = encryptor->decryptAll(data);
Address destAddr;
int header_length = 0;
bool _auth;
Common::parseHeader(data, destAddr, header_length, _auth);
if (header_length == 0) {
emit info("[UDP] Can't parse header. "
"Wrong encryption method or password?");
return;
}
response = QByteArray(3, static_cast<char>(0)) + data;
} else {
data.prepend(Common::packAddress(r_addr, r_port));
response = encryptor->encryptAll(data);
}
Address clientAddress = cache.key(sock);
if (clientAddress.getPort() != 0) {
listenSocket.writeDatagram(response,
clientAddress.getFirstIP(),
clientAddress.getPort());
} else {
emit debug("[UDP] Drop a packet from somewhere else we know.");
}
}
示例6: socket
SocketUDP::SocketUDP(char* ip, int port, bool broadcast){
this->sockId = socket(AF_INET, SOCK_DGRAM, 0); //this è una maniglia all'istanza corrente
if(broadcast){
enableBroadcast();
}
Address* mio = new Address(ip, port);
printf("IP: %s Port:%d\n", mio->getIp(), mio->getPort());
sockaddr_in* struttura = mio->toCompiledStructure();
bind(this->sockId, (struct sockaddr*)struttura, (socklen_t)sizeof(sockaddr_in));
free(struttura);
}
示例7: send
bool Socket::send(const Address& receiver, const void* data, int size)
{
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.S_un.S_addr = htonl(receiver.getAddress());
address.sin_port = htons(receiver.getPort());
//TODO handle partial packet sending through network
int bytesSent = sendto(m_socketHandle, (const char*) data, size, 0, (const sockaddr*) &address, sizeof(sockaddr_in));
return bytesSent == size;
}
示例8: connect
// peer
void Connection::connect(Address addr)
{
m_last_recieved = porting::getTimeMs();
//MutexAutoLock peerlock(m_peers_mutex);
//m_peers.lock_unique_rec();
auto node = m_peers.find(PEER_ID_SERVER);
if(node != m_peers.end()){
//throw ConnectionException("Already connected to a server");
ConnectionEvent ev(CONNEVENT_CONNECT_FAILED);
putEvent(ev);
}
m_enet_host = enet_host_create(NULL, 1, 0, 0, 0);
ENetAddress address;
#if defined(ENET_IPV6)
if (!addr.isIPv6())
inet_pton (AF_INET6, ("::ffff:"+addr.serializeString()).c_str(), &address.host);
else
address.host = addr.getAddress6().sin6_addr;
#else
if (addr.isIPv6()) {
//throw ConnectionException("Cant connect to ipv6 address");
ConnectionEvent ev(CONNEVENT_CONNECT_FAILED);
putEvent(ev);
} else {
address.host = addr.getAddress().sin_addr.s_addr;
}
#endif
address.port = addr.getPort();
ENetPeer *peer = enet_host_connect(m_enet_host, &address, CHANNEL_COUNT, 0);
peer->data = new u16;
*((u16*)peer->data) = PEER_ID_SERVER;
ENetEvent event;
int ret = enet_host_service (m_enet_host, & event, 5000);
if (ret > 0 && event.type == ENET_EVENT_TYPE_CONNECT) {
m_peers.set(PEER_ID_SERVER, peer);
m_peers_address.set(PEER_ID_SERVER, addr);
} else {
errorstream<<"connect enet_host_service ret="<<ret<<std::endl;
if (ret == 0) {
ConnectionEvent ev(CONNEVENT_CONNECT_FAILED);
putEvent(ev);
}
/* Either the 5 seconds are up or a disconnect event was */
/* received. Reset the peer in the event the 5 seconds */
/* had run out without any significant event. */
enet_peer_reset(peer);
}
}
示例9: l_get_server_info
// get_server_info()
int ModApiClient::l_get_server_info(lua_State *L)
{
Client *client = getClient(L);
Address serverAddress = client->getServerAddress();
lua_newtable(L);
lua_pushstring(L, client->getAddressName().c_str());
lua_setfield(L, -2, "address");
lua_pushstring(L, serverAddress.serializeString().c_str());
lua_setfield(L, -2, "ip");
lua_pushinteger(L, serverAddress.getPort());
lua_setfield(L, -2, "port");
lua_pushinteger(L, client->getProtoVersion());
lua_setfield(L, -2, "protocol_version");
return 1;
}
示例10: serve
// host
void Connection::serve(Address bind_addr)
{
ENetAddress address;
#if defined(ENET_IPV6)
address.host = bind_addr.getAddress6().sin6_addr; // in6addr_any;
#else
address.host = bind_addr.getAddress().sin_addr.s_addr; // ENET_HOST_ANY;
#endif
address.port = bind_addr.getPort(); // fmtodo
m_enet_host = enet_host_create(&address, g_settings->getU16("max_users"), CHANNEL_COUNT, 0, 0);
if (m_enet_host == NULL) {
ConnectionEvent ev(CONNEVENT_BIND_FAILED);
putEvent(ev);
}
}
示例11: initLocalMapSaving
void Client::initLocalMapSaving(const Address &address,
const std::string &hostname,
bool is_local_server)
{
if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
return;
}
const std::string world_path = porting::path_user
+ DIR_DELIM + "worlds"
+ DIR_DELIM + "server_"
+ hostname + "_" + to_string(address.getPort());
fs::CreateAllDirs(world_path);
m_localdb = new Database_SQLite3(world_path);
m_localdb->beginSave();
actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
}
示例12: initLocalMapSaving
void Client::initLocalMapSaving(const Address &address,
const std::string &hostname,
bool is_local_server)
{
m_localserver = nullptr;
m_localdb = NULL;
if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
return;
}
std::string address_replaced = hostname + "_" + to_string(address.getPort());
replace( address_replaced.begin(), address_replaced.end(), ':', '_' );
const std::string world_path = porting::path_user
+ DIR_DELIM + "worlds"
+ DIR_DELIM + "server_"
+ address_replaced;
SubgameSpec gamespec;
if (!getWorldExists(world_path)) {
gamespec = findSubgame(g_settings->get("default_game"));
if (!gamespec.isValid())
gamespec = findSubgame("minimal");
} else {
gamespec = findWorldSubgame(world_path);
}
fs::CreateAllDirs(world_path);
#if !MINETEST_PROTO
m_localserver = new Server(world_path, gamespec, false, false);
#endif
/*
m_localdb = new Database_SQLite3(world_path);
m_localdb->beginSave();
*/
actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
}
示例13: NetworkException
void
SocketBase::bindSocketTo(const Address& toaddr) throw(NetworkException)
{
if ( state == CONFIGURED )
{
int res = bind(sockfd, toaddr.getSockaddr(), toaddr.getSockaddrLen());
if(res == SOCKET_ERROR) {
lastError = GET_NET_ERROR();
doClose();
std::stringstream msg;
msg << "Couldn't bind socket to address '"
<< toaddr.getIP() << "' port " << toaddr.getPort()
<< ": " << NETSTRERROR(lastError);
throw NetworkException(msg.str());
}
SocketManager::addSocket(this);
state = BOUND;
}
else
{
LOGGER.warning("Trying to bind to a socket != CONFIGURED [%s]", getStateString());
}
}
示例14: packAddress
//pack a shadowsocks header
std::string Common::packAddress(const Address &addr)
{
std::string portNs(2, '\0');
qToBigEndian(addr.getPort(), reinterpret_cast<uchar*>(&portNs[0]));
std::string addrBin;
const Address::ATYP type = addr.addressType();
if (type == Address::HOST) {
const std::string& addressString = addr.getAddress();
//can't be longer than 255
addrBin = static_cast<char>(addressString.length()) + addressString;
} else if (type == Address::IPV4) {
uint32_t ipv4Address = qToBigEndian(addr.getFirstIP().toIPv4Address());
addrBin = std::string(reinterpret_cast<char*>(&ipv4Address), 4);
} else {
//Q_IPV6ADDR is a 16-unsigned-char struct (big endian)
Q_IPV6ADDR ipv6Address = addr.getFirstIP().toIPv6Address();
addrBin = std::string(reinterpret_cast<char*>(ipv6Address.c), 16);
}
char typeChar = static_cast<char>(type);
return typeChar + addrBin + portNs;
}
示例15: open
bool Port::open(const Contact& contact, bool registerName,
const char *fakeName) {
Contact contact2 = contact;
if (!NetworkBase::initialized()) {
YARP_ERROR(Logger::get(), "YARP not initialized; create a yarp::os::Network object before using ports");
return false;
}
ConstString n = contact2.getName();
if (n!="..." && n!="" && n[0]!='/') {
if (fakeName==NULL) {
YARP_SPRINTF1(Logger::get(),error,
"Port name '%s' needs to start with a '/' character",
n.c_str());
return false;
}
}
if (n!="..." && n!="") {
if (fakeName==NULL) {
ConstString prefix = NetworkBase::getEnvironment("YARP_PORT_PREFIX");
if (prefix!="") {
n = prefix + n;
contact2 = contact2.addName(n);
}
}
}
// Allow for open() to be called safely many times on the same Port
PortCoreAdapter *currentCore = &(HELPER(implementation));
if (currentCore->isOpened()) {
PortCoreAdapter *newCore = new PortCoreAdapter(*this);
YARP_ASSERT(newCore!=NULL);
// copy state that should survive in a new open()
if (currentCore->checkPortReader()!=NULL) {
newCore->configReader(*(currentCore->checkPortReader()));
}
if (currentCore->checkReadCreator()!=NULL) {
newCore->configReadCreator(*(currentCore->checkReadCreator()));
}
if (currentCore->checkWaitAfterSend()>=0) {
newCore->configWaitAfterSend(currentCore->checkWaitAfterSend());
}
close();
delete ((PortCoreAdapter*)implementation);
implementation = newCore;
}
PortCoreAdapter& core = HELPER(implementation);
core.openable();
bool local = false;
if (NetworkBase::localNetworkAllocation()&&contact2.getPort()<=0) {
YARP_DEBUG(Logger::get(),"local network allocation needed");
local = true;
}
bool success = true;
Address caddress(contact2.getHost().c_str(),
contact2.getPort(),
contact2.getCarrier().c_str(),
contact2.getName().c_str());
Address address = caddress;
core.setReadHandler(core);
if (contact2.getPort()>0 && contact2.getHost()!="") {
registerName = false;
}
if (registerName&&!local) {
Contact contactFull = NetworkBase::registerContact(contact2);
address = Address::fromContact(contactFull);
}
core.setControlRegistration(registerName);
success = (address.isValid()||local)&&(fakeName==NULL);
ConstString blame = "invalid address";
if (success) {
success = core.listen(address,registerName);
blame = "address conflict";
if (success) {
success = core.start();
blame = "manager did not start";
}
}
if (success) {
address = core.getAddress();
if (registerName&&local) {
contact2 = contact2.addSocket(address.getCarrierName().c_str(),
address.getName().c_str(),
address.getPort());
contact2 = contact2.addName(address.getRegName().c_str());
Contact newName = NetworkBase::registerContact(contact2);
core.resetPortName(newName.getName());
address = core.getAddress();
}
if (core.getVerbosity()>=1) {
YARP_INFO(Logger::get(),
//.........这里部分代码省略.........