void start_ethernet(IPAddress ipAddress, IPAddress netMask, IPAddress gateWay, netif_status_callback_fn status_cb) { struct ip_addr x_ip_addr, x_net_mask, x_gateway; extern err_t ethernetif_init(struct netif *netif); x_ip_addr.addr = ipAddress.GetV4LittleEndian(); if (x_ip_addr.addr == 0) { x_net_mask.addr = 0; x_gateway.addr = 0; } else { x_net_mask.addr = netMask.GetV4LittleEndian(); x_gateway.addr = gateWay.GetV4LittleEndian(); } /* Add data to netif */ netif_add(&gs_net_if, &x_ip_addr, &x_net_mask, &x_gateway, NULL, ethernetif_init, ethernet_input); /* Make it the default interface */ netif_set_default(&gs_net_if); /* Setup callback function for netif status change */ netif_set_status_callback(&gs_net_if, status_cb); /* Bring it up */ if (x_ip_addr.addr == 0) { /* DHCP mode */ dhcp_start(&gs_net_if); } else { /* Static mode */ netif_set_up(&gs_net_if); } }
bool EspDrv::getGateway(IPAddress& gw) { LOGDEBUG(F("> getGateway")); char buf[20]; if (sendCmdGet(F("AT+CIPSTA?"), F("+CIPSTA:gateway:\""), F("\""), buf, sizeof(buf))) { gw.fromString (buf); return true; } return false; }
bool EthernetClient::connect(IPAddress& host,int port) { fd = socket(AF_INET,SOCK_STREAM,0); if (fd == -1) return false; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(host.getAddress()); servaddr.sin_port = htons(port); int res = ::connect(fd,(struct sockaddr*)&servaddr,sizeof(servaddr)); return ( res != -1 ); } // connect(IPAddress&,...)
bool IPAddress::operator<(const IPAddress& ha) const { if (AddressFamily != ha.AddressFamily) return (int)get_AddressFamily() < (int)ha.get_AddressFamily(); switch ((int)get_AddressFamily()) { case AF_DOMAIN_NAME: return m_domainname < ha.m_domainname; case AF_INET: return memcmp(&m_sin.sin_addr, &ha.m_sin.sin_addr, 4) < 0; case AF_INET6: return memcmp(&m_sin6.sin6_addr, &ha.m_sin6.sin6_addr, 16) < 0; default: Throw(ExtErr::UnknownHostAddressType); } }
IPAddress IPAddress::operator ^ (const IPAddress& other) const { if (family() == other.family()) { if (family() == IPv4) { IPv4AddressImpl t(pImpl()->addr()); IPv4AddressImpl o(other.pImpl()->addr()); return IPAddress((t ^ o).addr(), sizeof(struct in_addr)); } #if defined(POCO_HAVE_IPv6) else if (family() == IPv6) { const IPv6AddressImpl t(pImpl()->addr(), pImpl()->scope()); const IPv6AddressImpl o(other.pImpl()->addr(), other.pImpl()->scope()); const IPv6AddressImpl r = t ^ o; return IPAddress(r.addr(), sizeof(struct in6_addr), r.scope()); } #endif else throw Poco::InvalidArgumentException("Invalid or unsupported address family passed to IPAddress()"); } else throw Poco::InvalidArgumentException("Invalid or unsupported address family passed to IPAddress()"); }
BinaryWriter& AFXAPI operator<<(BinaryWriter& wr, const IPAddress& ha) { wr << (short)ha.get_AddressFamily(); switch ((int)ha.get_AddressFamily()) { case AF_INET: wr.Write(&ha.m_sin.sin_addr, sizeof(ha.m_sin.sin_addr)); break; case AF_INET6: wr.Write(&ha.m_sin6.sin6_addr, sizeof(ha.m_sin6.sin6_addr)); break; default: wr.Write(&ha.m_sockaddr, sizeof(ha.m_sockaddr)); //!!! unknown size break; } return wr; }
bool UdpConnection::connect(IPAddress ip, uint16_t port) { if (udp == NULL) initialize(); if (udp->local_port == 0) { udp_bind(udp, IP_ADDR_ANY, 0); debugf("UDP LocalPort: %d", udp->local_port); } debugf("UDP connect to %s:%d", ip.toString().c_str(), port); err_t res = udp_connect(udp, ip, port); return res == ERR_OK; }
void NetworkInterfaceTest::testMap() { NetworkInterface::Map m = NetworkInterface::map(false, false); assert (!m.empty()); for (NetworkInterface::Map::const_iterator it = m.begin(); it != m.end(); ++it) { std::cout << std::endl << "=============" << std::endl; std::cout << "Index: " << it->second.index() << std::endl; std::cout << "Name: " << it->second.name() << std::endl; std::cout << "DisplayName: " << it->second.displayName() << std::endl; std::cout << "Status: " << (it->second.isUp() ? "Up" : "Down") << std::endl; NetworkInterface::MACAddress mac(it->second.macAddress()); if (!mac.empty() && (it->second.type() != NetworkInterface::NI_TYPE_SOFTWARE_LOOPBACK)) std::cout << "MAC Address: (" << it->second.type() << ") " << mac << std::endl; typedef NetworkInterface::AddressList List; const List& ipList = it->second.addressList(); List::const_iterator ipIt = ipList.begin(); List::const_iterator ipEnd = ipList.end(); for (int counter = 0; ipIt != ipEnd; ++ipIt, ++counter) { std::cout << std::endl << "----------" << std::endl; std::cout << "Address " << counter << std::endl; std::cout << "----------" << std::endl; std::cout << "Address: " << ipIt->get<NetworkInterface::IP_ADDRESS>() << std::endl; IPAddress addr = ipIt->get<NetworkInterface::SUBNET_MASK>(); if (!addr.isWildcard()) std::cout << "Subnet: " << addr << " (/" << addr.prefixLength() << ")" << std::endl; addr = ipIt->get<NetworkInterface::BROADCAST_ADDRESS>(); if (!addr.isWildcard()) std::cout << "Broadcast: " << addr << std::endl; } std::cout << "=============" << std::endl << std::endl; } }
bool EPDStreamer::connect(const char *host, uint16_t port) { if (connState != STATE_CONN_DISCONNECTED) { return false; } callbacksEnabled = true; IPAddress ip; connState = STATE_CONN_CONNECTING; Serial.print("Attempting connection to: "); Serial.print(host); Serial.print(":"); Serial.println(port); bool connectionSuccess; if (ip.fromString(host)) { Serial.println("Skipping name resolution"); connectionSuccess = client.connect(ip, port); } else { connectionSuccess = client.connect(host, port); } if (connectionSuccess) { Serial.println("Connected"); connState = STATE_CONN_CONNECTED; return true; } else { Serial.println("Connection failed"); connState = STATE_CONN_DISCONNECTED; return false; } }
void TunManager::addProbedAddr(int ifIndex, const IPAddress& addr, uint8_t mask) { for (auto& intf : intfs_) { if (intf.second->getIfIndex() == ifIndex) { intf.second->addAddress(addr, mask); return; } } // This function is called for all interface addresses discovered from // the host. Since we only create TunIntf object for TUN interfaces, // it is normal we cannot find the interface matching the ifIndex provided. VLOG(3) << "Cannot find interface @ index " << ifIndex << " for probed address " << addr.str() << "/" << static_cast<int>(mask); }
void SocketDefaultImpl::bind(const IPAddress &ip) { if (!isOpen()) open(); struct sockaddr_in addr; memset((void *)&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(ip.getPort()); addr.sin_addr.s_addr = htonl((unsigned)ip ? (unsigned)ip : INADDR_ANY); SysError::clear(); if (::bind((socket_t)socket, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR) THROWS("Could not bind socket to " << ip << ": " << SysError()); }
int EthernetClient::connect(IPAddress ip, uint16_t port) { if (m_sock) return 0; struct sockaddr_in sin = {0}; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = *(uint32_t*) (ip.raw_address()); m_sock = socket(AF_INET, SOCK_STREAM, 0); if (::connect(m_sock, (struct sockaddr *) &sin, sizeof(sin)) < 0) { trace("Error Connecting(%d)%s\n", errno, strerror(errno)); return false; } m_connected = true; return 1; }
bool WhiteListCache::IsWhitelisted(const String &fromAddress, const IPAddress &address) { // Create a lock for shared operations boost::upgrade_lock< boost::shared_mutex > lock(_whitelistAccessMutex); if (_needRefresh) { // We need exclusive access to be able to upade the cache boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock); Refresh(); } vector<shared_ptr<WhiteListAddress> >::iterator iter = _whitelistItems.begin(); vector<shared_ptr<WhiteListAddress> >::iterator iterEnd = _whitelistItems.end(); for (; iter != iterEnd; iter++) { shared_ptr<WhiteListAddress> pWhiteAddress = (*iter); IPAddress iLowerIP = pWhiteAddress->GetLowerIPAddress(); IPAddress iUpperIP = pWhiteAddress->GetUpperIPAddress(); if (address.WithinRange(iLowerIP, iUpperIP)) { String sWhiteEmailAddr = pWhiteAddress->GetEmailAddress(); if (sWhiteEmailAddr.IsEmpty() || sWhiteEmailAddr == _T("*")) { // White listed return true; } // Check if the senders email address matches if (StringParser::WildcardMatchNoCase(sWhiteEmailAddr, fromAddress)) { // White listed return true; } } } return false; }
HostEntry DNS::hostByAddress(const IPAddress& address, unsigned #ifdef POCO_HAVE_ADDRINFO hintFlags #endif ) { #if defined(POCO_HAVE_LIBRESOLV) Poco::ScopedReadRWLock readLock(resolverLock); #endif #if defined(POCO_HAVE_ADDRINFO) SocketAddress sa(address, 0); static char fqname[1024]; int rc = getnameinfo(sa.addr(), sa.length(), fqname, sizeof(fqname), NULL, 0, NI_NAMEREQD); if (rc == 0) { struct addrinfo* pAI; struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_flags = hintFlags; rc = getaddrinfo(fqname, NULL, &hints, &pAI); if (rc == 0) { HostEntry result(pAI); freeaddrinfo(pAI); return result; } else { aierror(rc, address.toString()); } } else { aierror(rc, address.toString()); } #elif defined(POCO_VXWORKS) char name[MAXHOSTNAMELEN + 1]; if (hostGetByAddr(*reinterpret_cast<const int*>(address.addr()), name) == OK) { return HostEntry(std::string(name), address); } #else struct hostent* he = gethostbyaddr(reinterpret_cast<const char*>(address.addr()), address.length(), address.af()); if (he) { return HostEntry(he); } #endif int err = lastError(); error(err, address.toString()); // will throw an appropriate exception throw NetException(); // to silence compiler }
HostBinding::HostBinding(IPAddress addr) : name(addr.toString()) { this->Init(); try { this->host = DNS::hostByAddress(addr); } catch (HostNotFoundException&) { this->invalid = true; //TODO: improve this exception so we can properly raise } catch (NoAddressFoundException&) { this->invalid = true; //TODO: improve this exception so we can properly raise } }
/** @details The broadcast address can only be calculated on a IPv4 network. While it is * technically possible to calculate an IPv6 broadcast address, the IPv6 protocol has dropped * support for broadcasting. Since broadcasting is not supported in IPv6, this method will result * in an exception given an IPv6 address. * @param ip An IP address on the network. * @param netmask The netmask defining the network range. * @returns The broadcast address. */ _CGUL_EXPORT CGUL::Network::IPAddress CGUL::Network::IPAddress::CalculateBroadcast(const IPAddress& ip, const IPAddress& netmask) { if (ip.GetType() == IPAddressType::IPV6 || netmask.GetType() == IPAddressType::IPV6) { throw NetworkException(NetworkExceptionCode::FAILED_CALCULATE_ADDRESS, NetworkExceptionReason::ADDRESS_INVALID); } if (!ip.IsValid() || ip.GetType() != netmask.GetType()) { throw NetworkException(NetworkExceptionCode::FAILED_CALCULATE_ADDRESS, NetworkExceptionReason::ADDRESS_MISMATCH); } return IPAddress(ip.ToUInt32() | (~netmask.ToUInt32())); }
void onReceive(UdpConnection& connection, char *data, int size, IPAddress remoteIP, uint16_t remotePort) { char buf[60]; char buf1[12]; sendToClients("UDP received"); debugf("UDP Sever callback from %s:%d, %d bytes", remoteIP.toString().c_str(), remotePort, size); // We implement string mode server for example Serial.print(">\t"); Serial.print(data); floatAnalog = atof(analogResult.c_str()) / 10.0; dtostrf(floatAnalog, 7, 4, buf1); sprintf(buf, "%s", deblank(buf1)); String message = String(buf); udp.sendStringTo(remoteIP, udpServerPort, message); }
//---------------------------------------------------------------------------- bool IPAddress::TryParse(const std::string &addr, IPAddress& result) { IPAddressImpl *impl = IPv4AddressImpl::Parse(addr); #if defined(PX2_HAVE_IPV6) if (!impl) { impl = IPv6AddressImpl::Parse(addr); } #endif if (impl) { result.Init(impl); return true; } return false; }
//Constructor UDPClient::UDPClient(int32_t v4_port, int32_t v6_port, const IPAddress& address): addr(address),myIP(myIPAddress::singleton()) { if(address.isIPv6()) slen=sizeof(ipv6_addr); else slen=sizeof(ipv4_addr); active = false; connected = false; intIPv4_Port = v4_port; intIPv6_Port = v6_port; conTrack = 0; resetVal = 15; broadcast = false; openSocket(); }
AsyncResultPtr Socket::BeginConnect(u_short port, IPAddress address, AsyncCallback callback, const ObjectPtr &asyncState) { AsyncResultPtr asyncResult(this, Nothing, asyncState, Nothing, callback); asyncResult->AddRef(); sockaddr_in name; name.sin_family = AF_INET; name.sin_port = htons(port); name.sin_addr.s_addr = htonl(address.Address()); SocketProvider &msp = SocketProvider::GetSingleton(); if (!msp.ConnectEx(hSocket, (SOCKADDR *)&name, sizeof(SOCKADDR), 0, 0, 0, asyncResult.operator ->()) && WSAGetLastError() != WSA_IO_PENDING) { asyncResult->Release(); throw Win32Exception("ConnectEx"); } return asyncResult; }
bool operator <(const IPAddress &a, const IPAddress &b) { for (int i = 0; i < 4; ++i) { if (a.part(i) < b.part(i)) { return true; } else if (a.part(i) > b.part(i)) { return false; } } return a.port() < b.port(); }
int WiFiClass::hostByName(const char* aHostname, IPAddress& aResult) { // check if aHostname is already an ipaddress if (aResult.fromString(aHostname)) { // if fromString returns true we have an IP address ready return 1; } else { // Network led ON (rev A then rev B). m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 0); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 0); // Send DNS request: _resolve = 0; if (gethostbyname((uint8 *)aHostname) < 0) { // Network led OFF (rev A then rev B). m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); return 0; } // Wait for connection or timeout: unsigned long start = millis(); while (_resolve == 0 && millis() - start < 20000) { m2m_wifi_handle_events(NULL); } // Network led OFF (rev A then rev B). m2m_periph_gpio_set_val(M2M_PERIPH_GPIO16, 1); m2m_periph_gpio_set_val(M2M_PERIPH_GPIO5, 1); if (_resolve == 0) { return 0; } aResult = _resolve; return 1; } }
HostEntry DNS::hostByAddress(const IPAddress& address) { NetworkInitializer networkInitializer; #if defined(POCO_HAVE_IPv6) || defined(POCO_HAVE_ADDRINFO) SocketAddress sa(address, 0); static char fqname[1024]; int rc = getnameinfo(sa.addr(), sa.length(), fqname, sizeof(fqname), NULL, 0, NI_NAMEREQD); if (rc == 0) { struct addrinfo* pAI; struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG; rc = getaddrinfo(fqname, NULL, &hints, &pAI); if (rc == 0) { HostEntry result(pAI); freeaddrinfo(pAI); return result; } else { aierror(rc, address.toString()); } } else { aierror(rc, address.toString()); } #elif defined(POCO_VXWORKS) char name[MAXHOSTNAMELEN + 1]; if (hostGetByAddr(*reinterpret_cast<const int*>(address.addr()), name) == OK) { return HostEntry(std::string(name), address); } #else struct hostent* he = gethostbyaddr(reinterpret_cast<const char*>(address.addr()), address.length(), address.af()); if (he) { return HostEntry(he); } #endif int err = lastError(); error(err, address.toString()); // will throw an appropriate exception throw NetException(); // to silence compiler }
DNSHandler::HostType DNSHandler::ResolvePTR (IPAddress ip) { // Hostname to query String name; if (ip.IsV6()) { // Convert the IPv6 address to an // integer auto num=static_cast<UInt128>(ip); // Extract each nibble for (Word i=0;i<(sizeof(num)*2);++i,num>>=4) name << String( num&static_cast<UInt128>( 15 // Low 4 bits set ), 16 // Hexadecimal ) << domain_separator; name << ipv6_ptr; } else {
// BEWARE blocking method!! bool DNS::HostByAddress(Exception& ex,const IPAddress& address, HostEntry& host) { if (!Net::InitializeNetwork(ex)) return false; SocketAddress sa; sa.set(address, 0); static char fqname[1024]; int rc = getnameinfo(sa.addr(), sa.size(), fqname, sizeof(fqname), NULL, 0, NI_NAMEREQD); if (rc == 0) { struct addrinfo* pAI; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG; rc = getaddrinfo(fqname, NULL, &hints, &pAI); if (rc == 0) { host.set(ex, pAI); freeaddrinfo(pAI); return true; } } SetAIError(ex, rc, " (address=",address.toString(),")"); return false; }
bool TCPServer::FireOnAcceptEvent(const IPAddress &remoteAddress, int port) { // Fire an event... if (!Configuration::Instance()->GetUseScriptServer()) return true; shared_ptr<ClientInfo> pCliInfo = shared_ptr<ClientInfo>(new ClientInfo); pCliInfo->SetIPAddress(remoteAddress.ToString()); pCliInfo->SetPort(port); shared_ptr<ScriptObjectContainer> pContainer = shared_ptr<ScriptObjectContainer>(new ScriptObjectContainer); shared_ptr<Result> pResult = shared_ptr<Result>(new Result); pContainer->AddObject("Result", pResult, ScriptObject::OTResult); pContainer->AddObject("HMAILSERVER_CLIENT", pCliInfo, ScriptObject::OTClient); String sEventCaller; String sScriptLanguage = Configuration::Instance()->GetScriptLanguage(); if (sScriptLanguage == _T("VBScript")) sEventCaller.Format(_T("OnClientConnect(HMAILSERVER_CLIENT)")); else if (sScriptLanguage == _T("JScript")) sEventCaller.Format(_T("OnClientConnect(HMAILSERVER_CLIENT);")); ScriptServer::Instance()->FireEvent(ScriptServer::EventOnClientConnect, sEventCaller, pContainer); switch (pResult->GetValue()) { case 1: { // Disconnect the socket immediately. return false; } } return true; }
//////////////////////////////////////////////////////////// /// Send an array of bytes //////////////////////////////////////////////////////////// Socket::Status SocketUDP::Send(const char* Data, std::size_t Size, const IPAddress& Address, unsigned short Port) { // Make sure the socket is valid if (!IsValid()) Create(); // Check parameters if (Data && Size) { // Build the target address sockaddr_in Target; Target.sin_family = AF_INET; Target.sin_port = htons(Port); Target.sin_addr.s_addr = inet_addr(Address.ToString().c_str()); memset(Target.sin_zero, 0, sizeof(Target.sin_zero)); // Loop until every byte has been sent int Sent = 0; int SizeToSend = static_cast<int>(Size); for (int Length = 0; Length < SizeToSend; Length += Sent) { // Send a chunk of data Sent = (int)sendto(mySocket, Data + Length, SizeToSend - Length, 0, reinterpret_cast<sockaddr*>(&Target), sizeof(Target)); // Check errors if (Sent <= 0) return SocketHelper::GetErrorStatus(); } return Socket::Done; } else { // Error... std::cerr << "Cannot send data over the network (invalid parameters)" << std::endl; return Socket::Error; } }
//////////////////////////////////////////////////////////// /// Connect to another computer on a specified port //////////////////////////////////////////////////////////// bool SocketTCP::Connect(unsigned short Port, const IPAddress& HostAddress) { // Make sure our socket is valid if (!IsValid()) Create(); // Build the host address sockaddr_in SockAddr; memset(SockAddr.sin_zero, 0, sizeof(SockAddr.sin_zero)); SockAddr.sin_addr.s_addr = inet_addr(HostAddress.ToString().c_str()); SockAddr.sin_family = AF_INET; SockAddr.sin_port = htons(Port); // Connect if (connect(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) == -1) { // Error... std::cerr << "Failed to connect socket to host " << HostAddress << std::endl; return false; } return true; }
void Socket::Connect(IPAddress &remoteAddress, unsigned short remotePort) { struct sockaddr_in sockin; // Fill the struct. sockin.sin_family = AF_INET; sockin.sin_addr.s_addr = inet_addr( remoteAddress.toString() ); sockin.sin_port = htons( remotePort ); // Fill in internal storage variables. connectAddr = remoteAddress; RemotePort = remotePort; // Attempt a connection. if ( connect( connection, (const sockaddr *)&sockin, sizeof(sockin) ) == SOCKET_ERROR ) { Log::Msg("Could not connect to the server.", Log::FatalError); } else { Log::Msg("Successfully connected to the server.", Log::Info); } }
int32_t MTD_FLASHMEM ICMP::ping(IPAddress const& dest) { static uint32_t const TIMEOUT = 4000; static int32_t const TIMEOUT_RESULT = -1; uint32_t result = TIMEOUT_RESULT; // generate seq m_waitingSeq++; // prepare packet to send pbuf* hdrbuf = pbuf_alloc(PBUF_IP, sizeof(icmp_echo_hdr), PBUF_RAM); icmp_echo_hdr* hdr = (icmp_echo_hdr*)hdrbuf->payload; hdr->type = ICMP_ECHO; hdr->code = 0; hdr->chksum = 0; hdr->id = htons(m_waitingID); hdr->seqno = htons(m_waitingSeq); hdr->chksum = inet_chksum((uint16_t*)hdr, sizeof(icmp_echo_hdr)); // send Echo request raw_pcb* pcb = raw_new(IP_PROTO_ICMP); raw_recv(pcb, ICMP::raw_recv_fn, this); raw_bind(pcb, IP_ADDR_ANY); ip_addr_t addr = dest.get_ip_addr_t(); raw_sendto(pcb, hdrbuf, &addr); pbuf_free(hdrbuf); uint32_t t1 = micros(); if (m_queue.receive(TIMEOUT)) result = (micros() - t1); raw_remove(pcb); return result; }