bool I_IpServerTransport::isIpAllowed(const IpAddress &ip) const { ReadLock readLock(mReadWriteMutex); if (!mAllowedIps.empty()) { for (std::size_t i=0; i<mAllowedIps.size(); ++i) { if (ip.matches(mAllowedIps[i].first, mAllowedIps[i].second)) { return true; } } return false; } if (!mDisallowedIps.empty()) { for (std::size_t i=0; i<mDisallowedIps.size(); ++i) { if (ip.matches(mDisallowedIps[i].first, mDisallowedIps[i].second)) { return false; } } return true; } return true; }
YETI_Result HttpTcpConnector::connect(const HttpUrl & url, HttpClient & client, const HttpProxyAddress * proxy, bool reuse, HttpClient::Connection *& connection) { connection = NULL; const char * server_hostname; YETI_UInt16 server_port; if (proxy) { server_hostname = (const char *)proxy->get_hostname(); server_port = proxy->get_port(); } else { server_hostname = (const char *)url.get_host(); server_port = url.get_port(); } IpAddress address; YETI_CHECK_FINE(address.resolve_name(server_hostname, client.get_config().m_name_resolver_timeout_)); YETI_LOG_FINE_2("TCP connector will connect to %s : %d", server_hostname, server_port); TcpClientSocket * tcp_socket = new TcpClientSocket(); SocketReference socket(tcp_socket, true); tcp_socket->set_read_timeout(client.get_config().m_io_timeout_); tcp_socket->set_write_timeout(client.get_config().m_io_timeout_); SocketAddress socket_address(address, server_port); YETI_CHECK_FINE(tcp_socket->connect(socket_address, client.get_config().m_connection_timeout_)); HttpSimpleConnection * _connection = new HttpSimpleConnection(); _connection->m_socket_ = socket; connection = _connection; tcp_socket->get_input_stream(_connection->m_inputstream_); tcp_socket->get_output_stream(_connection->m_outputstream_); return YETI_SUCCESS; }
void ClusterMembership::decodeMasterPacket(const char *buf, int len, const IpAddress & src) { // NOTE: Should we check the src address as being // the master we know and love? if (len < 21) { // packet is too small to be a valid master packet. return; } int numnodes = (int) (buf[20]); // A master announcement is only helpful if there is at least // one node in it, and fewer than the max if ((numnodes < 1) || (numnodes > MaxNodes)) { return; } // We need 12 bytes per node if (len < (21 + (12 * numnodes))) { // too small for the number of nodes. return; } int newLower = 0; int newUpper = 0; const char *nodebuf = (buf + 21); for (int i=0; i< numnodes; i++) { int offset = (i * 12); IpAddress ip; ip.copyFromInAddr((struct in_addr *) (nodebuf+offset)); if (ip == localaddr) { newLower = ntohl(*(int *)(nodebuf + offset + 4)); newUpper = ntohl(*(int *)(nodebuf + offset + 8)); } } setNewLocalBoundaries(newLower, newUpper); }
void TcpClient::connect(const IpAddress& address, NetPort port, const Duration& timeout, const Duration& pause) { Expect(address.isValid(), Throw(InvalidParameter, "Invalid IpAddress")); Expect(port != NetPort_Any, Throw(InvalidParameter, "Invalid NetPort")); int ret; Clock clock; Socket::create(address.getProtocol()); prv::SockAddrBuffer buffer(address, port); clock.start(); do { ret = ::connect(getHandler(), buffer.getSockAddr(), buffer.getLength()); if(ret != 0) { std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<long long>(pause.asMilliseconds()))); } }while(ret != 0 && clock.getElapsedTime() < timeout); Expect(ret == 0, Throw(InternalError, "Failed to connect to the remote host")); }
int main(int argc, char* argv[]) { InitModuleObjects(); EnableSEHtoExceptionMapping(); if (argc<6) { usage(); return 0; } try { const char *filename = argv[1]; Owned<IDaliCapabilityCreator> cc = createDaliCapabilityCreator(); cc->setSystemID(argv[2]); cc->setServerPassword(argv[3]); for (unsigned i=4;i<argc;i++) { const char *cmd = argv[i++]; if (i==argc) break; const char *param = argv[i]; if (stricmp(cmd,"THORWIDTH")==0) { cc->setLimit(DCR_ThorSlave,atoi(param)); } else if (stricmp(cmd,"DALINODE")==0) { StringBuffer mac; if (strchr(param,'.')) { // must be ip IpAddress ip; ip.set(param); if (!getMAC(ip,mac)) { printf("ERROR: could mot get MAC address for %s\n",param); return 1; } } else mac.append(param); cc->addCapability(DCR_DaliServer,mac.str()); } else { printf("ERROR: unknown command %s\n",cmd); return 1; } } StringBuffer results; cc->save(results); Owned<IFile> ifile = createIFile(filename); Owned<IFileIO> ifileio = ifile->open(IFOcreate); ifileio->write(0,results.length(),results.str()); printf("Dali Capabilities sucessfully exported to %s\n", filename); } catch (IException *e) { EXCLOG(e); e->Release(); } releaseAtoms(); return 0; }
bool Proxy::sendMsgBlock(MsgBlockType type, const IpAddress &remote_ip, const void *data, unsigned len) { //cout << "> type=" << type << " remote_ip=" << remote_ip // << " len=" << len << endl; if (!con.isConnected() || (state != STATE_CONNECTED)) { return false; } int msg_len = MSG_HEADER_SIZE + len; uint8_t msg_buf[msg_len]; uint8_t *msg_ptr = msg_buf; // Store the message type *msg_ptr++ = static_cast<uint8_t>(type); // Store the proxied remote IP address if set in_addr_t remote_ip_addr = 0; if (!remote_ip.isEmpty()) { remote_ip_addr = remote_ip.ip4Addr().s_addr; } *msg_ptr++ = remote_ip_addr & 0xff; *msg_ptr++ = (remote_ip_addr >> 8) & 0xff; *msg_ptr++ = (remote_ip_addr >> 16) & 0xff; *msg_ptr++ = (remote_ip_addr >> 24) & 0xff; // Store the message data length *msg_ptr++ = len & 0xff; *msg_ptr++ = (len >> 8) & 0xff; *msg_ptr++ = (len >> 16) & 0xff; *msg_ptr++ = (len >> 24) & 0xff; // Store the message data memcpy(msg_ptr, data, len); // Send the message int ret = con.write(msg_buf, msg_len); if (ret == -1) { char errstr[256]; errstr[0] = 0; strerror_r(errno, errstr, sizeof(errstr)); cerr << "*** ERROR: Error while writing message to EchoLink proxy: " << errstr << endl; reset(); } else if (ret != msg_len) { cerr << "*** ERROR: Could not write all data to EchoLink proxy\n"; reset(); } return true; } /* Proxy::sendMsgBlock */
bool Configurator::writeIp (std::ostream &stream, const IpAddress &address) { if (!writeInt(stream, address.family())) return false; if (!stream.write(reinterpret_cast<const char *>(address.data()), address.size()) || !stream.good()) return false; return true; }
void TcpClient::connect(const IpAddress& address, NetPort port) { Expect(address.isValid(), Throw(InvalidParameter, "Invalid IpAddress")); Expect(port != NetPort_Any, Throw(InvalidParameter, "Invalid NetPort")); Socket::create(address.getProtocol()); prv::SockAddrBuffer buffer(address, port); int ret = ::connect(getHandler(), buffer.getSockAddr(), buffer.getLength()); Expect(ret == 0, Throw(InternalError, "Failed to connect to the remote host")); }
SocketState TcpServer::Listen(const IpAddress& address, unsigned int queueSize) { NazaraAssert(address.IsValid(), "Invalid address"); Open(address.GetProtocol()); SocketState state = SocketImpl::Listen(m_handle, address, queueSize, &m_lastError); if (state == SocketState_Bound) m_boundAddress = SocketImpl::QuerySocketAddress(m_handle); UpdateState(state); return state; }
//For every ECLWatchVisible dropzones, read: dropZoneName, directory, and, if available, computer. //For every Servers/Server in ECLWatchVisible dropzones, read: directory, // server name, and hostname(or IP). Create dropzone("@name", "@directory", "@computer", // "@netAddress", "@linux", "@sourceNode") tree into pSoftware. void CFileSpraySoapBindingEx::appendDropZones(double clientVersion, IConstEnvironment* env, const char* dfuwuidSourcePartIP, IPropertyTree* softwareTree) { Owned<IConstDropZoneInfoIterator> dropZoneItr = env->getDropZoneIterator(); ForEach(*dropZoneItr) { IConstDropZoneInfo& dropZoneInfo = dropZoneItr->query(); if (!dropZoneInfo.isECLWatchVisible()) //This code is used by ECLWatch. So, skip the DZs not for ECLWatch. continue; SCMStringBuffer dropZoneName, directory, computerName; dropZoneInfo.getName(dropZoneName); dropZoneInfo.getDirectory(directory); if (!dropZoneName.length() || !directory.length()) continue; bool isLinux = getPathSepChar(directory.str()) == '/' ? true : false; Owned<IConstDropZoneServerInfoIterator> dropZoneServerItr = dropZoneInfo.getServers(); ForEach(*dropZoneServerItr) { IConstDropZoneServerInfo& dropZoneServer = dropZoneServerItr->query(); StringBuffer name, server, networkAddress; dropZoneServer.getName(name); dropZoneServer.getServer(server); if (name.isEmpty() || server.isEmpty()) continue; IPropertyTree* dropZone = softwareTree->addPropTree("DropZone", createPTree()); dropZone->setProp("@name", dropZoneName.str()); dropZone->setProp("@computer", name.str()); dropZone->setProp("@directory", directory.str()); if (isLinux) dropZone->setProp("@linux", "true"); IpAddress ipAddr; ipAddr.ipset(server.str()); ipAddr.getIpText(networkAddress); if (!ipAddr.isNull()) { dropZone->addProp("@netAddress", networkAddress); if (!isEmptyString(dfuwuidSourcePartIP)) { IpAddress ip(dfuwuidSourcePartIP); if (ip.ipequals(ipAddr)) dropZone->addProp("@sourceNode", "1"); } } } } }
bool UdpSocket::Send(const IpAddress& to, const void* buffer, std::size_t size, std::size_t* sent) { NazaraAssert(to.IsValid(), "Invalid ip address"); NazaraAssert(to.GetProtocol() == m_protocol, "IP Address has a different protocol than the socket"); NazaraAssert(buffer && size > 0, "Invalid buffer"); int byteSent; if (!SocketImpl::SendTo(m_handle, buffer, static_cast<int>(size), to, &byteSent, &m_lastError)) return false; if (sent) *sent = byteSent; return true; }
/*! * \brief Sends multiple buffers as one datagram * \return true If data were sent * * \param to Destination IpAddress (must match socket protocol) * \param buffers A pointer to an array of NetBuffer containing buffers and size data * \param size Number of NetBuffer to send * \param sent Optional argument to get the number of bytes sent */ bool UdpSocket::SendMultiple(const IpAddress& to, const NetBuffer* buffers, std::size_t bufferCount, std::size_t* sent) { NazaraAssert(to.IsValid(), "Invalid ip address"); NazaraAssert(to.GetProtocol() == m_protocol, "IP Address has a different protocol than the socket"); NazaraAssert(buffers && bufferCount > 0, "Invalid buffer"); int byteSent; if (!SocketImpl::SendMultiple(m_handle, buffers, bufferCount, to, &byteSent, &m_lastError)) return false; if (sent) *sent = byteSent; return true; }
void Acceptor::helpStop() { Socket client; if ( client.CreateTcpSocket() ) { IpAddress addr; addr.Init( _T("127.0.0.1"), m_socket->GetAddress().GetPort() ); (void)client.Connect( m_socket->GetAddress() ); (void)client.Connect( addr ); } }
SocketState SocketImpl::Listen(SocketHandle handle, const IpAddress& address, unsigned queueSize, SocketError* error) { NazaraAssert(handle != InvalidHandle, "Invalid handle"); NazaraAssert(address.IsValid(), "Invalid address"); IpAddressImpl::SockAddrBuffer nameBuffer; int bufferLength = IpAddressImpl::ToSockAddr(address, nameBuffer.data()); if (bind(handle, reinterpret_cast<const sockaddr*>(&nameBuffer), bufferLength) == SOCKET_ERROR) { if (error) *error = TranslateWSAErrorToSocketError(WSAGetLastError()); return SocketState_NotConnected; } if (listen(handle, queueSize) == SOCKET_ERROR) { if (error) *error = TranslateWSAErrorToSocketError(WSAGetLastError()); return SocketState_NotConnected; } if (error) *error = SocketError_NoError; return SocketState_Bound; }
void TcpClientBase::connect(const IpAddress& remote_ip, uint16_t remote_port) { con->setRemoteAddr(remote_ip); remote_host = remote_ip.toString(); con->setRemotePort(remote_port); connect(); } /* TcpClientBase::connect */
Socket::Status UdpSocket::send(const void* data, std::size_t size, const IpAddress& remoteAddress, unsigned short remotePort) { // Create the internal socket if it doesn't exist create(); // Make sure that all the data will fit in one datagram if (size > MaxDatagramSize) { err() << "Cannot send data over the network " << "(the number of bytes to send is greater than cpp3ds::UdpSocket::MaxDatagramSize)" << std::endl; return Error; } // Build the target address sockaddr_in address = priv::SocketImpl::createAddress(remoteAddress.toInteger(), remotePort); // Send the data (unlike TCP, all the data is always sent in one call) int sent = sendto(getHandle(), static_cast<const char*>(data), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&address), sizeof(address)); // Check for errors if (sent < 0) return priv::SocketImpl::getErrorStatus(); return Done; }
void ClusterMembership::handleSetWeight(const char *buf, int len, const IpAddress & src) { // "Set Weight" packets always must come from localhost, IpAddress localhost; localhost.copyFromString("127.0.0.1"); if (src != localhost) { // Bad. return; } // their source IP and cluster IP fields are present but ignored. unsigned int desiredWeight = ntohl(*(int *) (buf + 16)); // Set our own node's weight std::cout << "Setting weight to " << desiredWeight << std::endl; weight = desiredWeight; }
static void multisetup(int sock, const IpAddress &bindaddr, int ifindex) { inet_aton("239.255.42.99", &multiaddr); struct ip_mreqn mr; mr.imr_multiaddr = multiaddr; bindaddr.copyToInAddr(& mr.imr_address); mr.imr_ifindex = ifindex; int res = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, & mr, sizeof(mr)); if (res == -1) { throw std::runtime_error("join multicast grp"); } int loop = 1; res = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); if (res == -1) { throw std::runtime_error("multicast loop"); } res = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &mr, sizeof(mr)); if (res == -1) { throw std::runtime_error("multicast interface"); } }
TcpClient::TcpClient(const IpAddress& remote_ip, uint16_t remote_port, size_t recv_buf_len) : TcpConnection(recv_buf_len), dns(0), remote_host(remote_ip.toString()), sock(-1), wr_watch(0) { setRemoteAddr(remote_ip); setRemotePort(remote_port); } /* TcpClient::TcpClient */
MacAddress MacAddress::lookup_from_ip_with_arp_table(const IpAddress& ipAddress, bool ping) { if(!ipAddress.isValid()) { return MacAddress(); } char line[500]; char ip_address[500]; int hw_type; int flags; char mac_address[500]; char mask[500]; char device[500]; MacAddress foundMac; if (ping) { ipAddress.ping(1000); } // ARP Table Reading Suggestion From // http://stackoverflow.com/a/21031888 FILE *fp = fopen("/proc/net/arp", "r"); fgets(line, sizeof(line), fp); // Skip the first line (column headers). while(fgets(line, sizeof(line), fp)) { sscanf(line, "%s 0x%x 0x%x %s %s %s\n", ip_address, &hw_type, &flags, mac_address, mask, device); if (ipAddress.toString().compare(ip_address) == 0) { foundMac = MacAddress(mac_address); break; } } fclose(fp); return foundMac; }
Status TcpSocket::connect(IpAddress const &remote) { socket_details::sockaddr_t addr = remote.toSockaddr(); int ret = ::connect(mHandle, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)); if(ret < 0) { return getLastError(); }else { return net::Ok; } }
TcpClientBase::TcpClientBase(TcpConnection *con, const IpAddress& remote_ip, uint16_t remote_port) : con(con), dns(0), remote_host(remote_ip.toString()), sock(-1), wr_watch(0) { con->setRemoteAddr(remote_ip); con->setRemotePort(remote_port); wr_watch = new FdWatch; wr_watch->activity.connect(mem_fun(*this, &TcpClientBase::connectHandler)); } /* TcpClientBase::TcpClientBase */
String IpAddress::ResolveAddress(const IpAddress& address, String* service, ResolveError* error) { NazaraAssert(address.IsValid(), "Invalid address"); String hostname; IpAddressImpl::ResolveAddress(address, &hostname, service, error); return hostname; }
void HostContacts::deserialize(NetworkInterface *iface, GenericHost *h, json_object *o) { json_object *obj; IpAddress ip; if(!o) return; /* Reset all */ memset(clientContacts, 0, sizeof(clientContacts)); memset(serverContacts, 0, sizeof(serverContacts)); if(json_object_object_get_ex(o, "client", &obj)) { struct json_object_iterator it = json_object_iter_begin(obj); struct json_object_iterator itEnd = json_object_iter_end(obj); while (!json_object_iter_equal(&it, &itEnd)) { char *key = (char*)json_object_iter_peek_name(&it); int value = json_object_get_int(json_object_iter_peek_value(&it)); ip.set_from_string(key); incrContact(iface, h->get_host_serial(), &ip, true /* client */, value, HOST_FAMILY_ID, false); //ntop->getTrace()->traceEvent(TRACE_WARNING, "%s=%d", key, value); json_object_iter_next(&it); } } if(json_object_object_get_ex(o, "server", &obj)) { struct json_object_iterator it = json_object_iter_begin(obj); struct json_object_iterator itEnd = json_object_iter_end(obj); while (!json_object_iter_equal(&it, &itEnd)) { char *key = (char*)json_object_iter_peek_name(&it); int value = json_object_get_int(json_object_iter_peek_value(&it)); ip.set_from_string(key); incrContact(iface, h->get_host_serial(), &ip, false /* server */, value, HOST_FAMILY_ID, false); // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s=%d", key, value); json_object_iter_next(&it); } } }
Status TcpSocket::accept(socket_details::socket_t &peer, IpAddress &remoteAddress) { socket_details::sockaddr_t addr; unsigned int addrLen = sizeof(addr); peer = ::accept(mHandle, reinterpret_cast<sockaddr*>(&addr), &addrLen); if(peer < 0) { return getLastError(); } remoteAddress.set(addr); return net::Ok; }
int my_send() { printf("==== Send\n"); char * msg = "hello"; UdpSocket sender; DataBuffer buffer(1024); buffer.set_data_size(1024); buffer.set_data((YETI_Byte *)msg, strlen(msg)); IpAddress address; address.resolve_name("localhost"); SocketAddress socket_address(address, 9123); YETI_Result result = sender.send(buffer, &socket_address); if (YETI_FAILED(result)) { fprintf(stderr, "send() failed (%d)\n", result); return result; } return 0; }
SocketState UdpSocket::Bind(const IpAddress& address) { NazaraAssert(m_handle != SocketImpl::InvalidHandle, "Socket hasn't been created"); NazaraAssert(address.IsValid(), "Invalid address"); SocketState state = SocketImpl::Bind(m_handle, address, &m_lastError); if (state == SocketState_Bound) m_boundAddress = SocketImpl::QuerySocketAddress(m_handle); UpdateState(state); return state; }
std::vector<IpAddress> SocketToolkit::ipAddressInfo() { std::vector<IpAddress> ipaddrs; char errbuf[PCAP_ERRBUF_SIZE]; pcap_if_t *alldevs = NULL; /* get all device */ if (pcap_findalldevs(&alldevs, errbuf) == -1) { LOG_ERROR(QObject::tr( "Error in pcap_findalldevs: %1").arg( errbuf)); return ipaddrs; } if (alldevs == NULL) { LOG_ERROR("No interfaces found! Make sure WinPcap is installed."); return ipaddrs; } pcap_if_t *device = NULL; for (device = alldevs; device; device = device->next) { IpAddress addr; pcap_addr_t *local_address; //get ip address for (local_address = device->addresses; local_address != NULL; local_address = local_address->next) { if (local_address->addr->sa_family == AF_INET) { addr.set_version(IpAddress::IPV4); struct sockaddr_in * sin = (struct sockaddr_in *)local_address->addr; addr.set_ipv4(sin->sin_addr.s_addr); ipaddrs.push_back(addr); } else if(local_address->addr->sa_family == AF_INET6) { addr.set_version(IpAddress::IPV6); struct sockaddr_in6 * sin = (struct sockaddr_in6 *)local_address->addr; addr.set_ipv6((char*)&sin->sin6_addr); ipaddrs.push_back(addr); } } } pcap_freealldevs(alldevs); return ipaddrs; }
bool IpWidget::preSendData() { if (m_ip != NULL) { LOG_ERROR(tr("'preSendData' function has been called")); return false; } int protocol = ui.protocol_box->getIntStrValue().toInt(); QString all_dstip = ui.dip_edit->text(); QStringList dstip_list = all_dstip.split(','); m_dstip.clear(); for (int i = 0; i < dstip_list.size(); i++) { std::string dstip = dstip_list[i].toLocal8Bit().constData(); if (dstip.empty()) { continue; } IpAddress addr; bool ret = addr.from_string(dstip); if (!ret) { LOG_ERROR(tr("invaild dst ip: %1").arg(dstip.c_str())); return false; } m_dstip.push_back(addr); } if (m_dstip.size() == 0 || protocol == 0) { LOG_ERROR(tr("ip and protocol must set")); return false; } if (ui.default_box->checkState() == Qt::Checked) { m_ip = new Ip(protocol); } else { IpAddress src_addr = ui.sip_box->getIpAddress(); m_ip = new Ip(protocol, src_addr); } return true; }
void UdpSocketBaton::send(IpAddress adr, const char* data, size_t len) { UdpSend* baton = new UdpSend; baton->handle.data = baton; baton->buffer = memdup(data, len); int r = uv_udp_send(&(baton->handle), &handle, &(baton->buffer), 1, adr.c_obj(), &on_udp_send); if (r != 0) { throw std::logic_error(uv_strerror(r)); } start_recive(); }