Nequeo::Net::Sockets::HostEntry Nequeo::Net::Sockets::DNS::hostByAddress(const IPAddress& address) { NetworkInitializer networkInitializer; 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()); } int err = lastError(); error(err, address.toString()); // will throw an appropriate exception throw Nequeo::Exceptions::Net::NetException(); // to silence compiler }
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 }
void STAGotIP(IPAddress ip, IPAddress mask, IPAddress gateway) { debugf("GOTIP - IP: %s, MASK: %s, GW: %s\n", ip.toString().c_str(), mask.toString().c_str(), gateway.toString().c_str()); if (WifiAccessPoint.isEnabled()) { debugf("Shutdown OWN AP"); WifiAccessPoint.enable(false); } // Add commands to be executed after successfully connecting to AP and got IP from it }
void udp_recieve(UdpConnection& connection, char *data, int size, IPAddress remoteIP, uint16_t remotePort) { debugf("UDP Sever callback from %s:%d, %d bytes", remoteIP.toString().c_str(), remotePort, size); debugf("UDP Data: %s", data); DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); if( !strcmp( data, "enum" ) ){ root.addCopy("ip", WifiStation.getIP().toString()); root.add("pos", driver_pos()); udp.sendStringTo(remoteIP, remotePort, root.toJsonString().c_str()); debugf("Sending to IP:%s:%d resp:%s", remoteIP.toString().c_str(), remotePort, root.toJsonString().c_str()); } else { debugf("UDP Unknown packet : %s", data); } }
void BaosIpEnumerator::addDevice(const std::vector<unsigned char>& buffer, const IPAddress& networkInterface) { if (buffer.size() > 68) { const int svcdiblen = buffer.at(68); const std::string ipAddress = format("%d.%d.%d.%d", (int) buffer.at(8), (int) buffer.at(9), (int) buffer.at(10), (int) buffer.at(11)); const std::string deviceName = extract(&buffer.at(38), 30); const int manOffset = 68 + svcdiblen; if (static_cast<std::size_t>(manOffset + 7) < buffer.size()) { const unsigned short mancode = buffer.at(manOffset + 2) << 8 | buffer.at(manOffset + 3); const unsigned char protocol = buffer.at(manOffset + 6); const unsigned char version = buffer.at(manOffset + 7); if (mancode == 0x00C5 && protocol == 0xF0) { poco_information(LOGGER(), format("Found: %s %s %d", deviceName, ipAddress, static_cast<int>(version))); devices_.push_back(std::make_tuple(deviceName, networkInterface.toString(), ipAddress, version)); } } } }
/** * Resolve the given hostname to an IP address. * @param aHostname Name to be resolved * @param aResult IPAddress structure to store the returned IP address * @return 1 if aIPAddrString was successfully converted to an IP address, * else error code */ int ESP8266WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult) { ip_addr_t addr; aResult = static_cast<uint32_t>(0); if(aResult.fromString(aHostname)) { // Host name is a IP address use it! DEBUG_WIFI_GENERIC("[hostByName] Host: %s is a IP!\n", aHostname); return 1; } DEBUG_WIFI_GENERIC("[hostByName] request IP for: %s\n", aHostname); err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult); if(err == ERR_OK) { aResult = addr.addr; } else if(err == ERR_INPROGRESS) { esp_yield(); // will return here when dns_found_callback fires if(aResult != 0) { err = ERR_OK; } } if(err != 0) { DEBUG_WIFI_GENERIC("[hostByName] Host: %s lookup error: %d!\n", aHostname, err); } else { DEBUG_WIFI_GENERIC("[hostByName] Host: %s IP: %s\n", aHostname, aResult.toString().c_str()); } return (err == ERR_OK) ? 1 : 0; }
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 }
void loop() { if (WiFi.ready()) { if (firstTimeReady) { firstTimeReady = false; // First time we get WiFi.ready(), initialize the UDP listener. This happens // every time we reconnect to WiFi. mcastUdp.begin(MCAST_PORT); } if (!haveServerAddr && millis() - serverAddrLastCheck >= SERVER_ADDR_CHECK_RETRY_MS) { serverAddrLastCheck = millis(); // If we don't have a server IP address, request it periodically (every 20 seconds) Serial.printlnf("requesting server address at %s:%d", mcastAddr.toString().c_str(), MCAST_PORT); strcpy(udpBuffer, "\n"); mcastUdp.sendPacket(udpBuffer, strlen(udpBuffer), mcastAddr, MCAST_PORT); } int count = mcastUdp.receivePacket(udpBuffer, UDP_BUFFER_SIZE - 1); if (count > 0) { udpBuffer[count] = 0; // Handle a received UDP packet from the server with the IP address and port of the server int addr[4], port; if (sscanf(udpBuffer, "%u.%u.%u.%u:%u", &addr[0], &addr[1], &addr[2], &addr[3], &port) == 5) { serverAddr = IPAddress(addr[0], addr[1], addr[2], addr[3]); serverPort = port; haveServerAddr = true; Serial.printlnf("serverAddr=%s port=%d", serverAddr.toString().c_str(), serverPort); } } } else { // If WiFi disconnects, we need to reestablish listeners next time firstTimeReady = true; } }
void UdpConnection::sendTo(IPAddress remoteIP, uint16_t remotePort, const char* data, int length) { remotePort = 1000; pbuf* p = pbuf_alloc(PBUF_TRANSPORT, length, PBUF_RAM); memcpy(p->payload, data, length); udp_sendto(udp, p, remoteIP, remotePort); pbuf_free(p); debugf("UdpConnection sendTo : %s %d %s", remoteIP.toString().c_str(),remotePort, data); }
void DNSServer::onReceive(pbuf* buf, IPAddress remoteIP, uint16_t remotePort) { if (_buffer != NULL) free(_buffer); _buffer = (char*)malloc(buf->tot_len * sizeof(char)); if (_buffer == NULL) return; pbuf_copy_partial(buf, _buffer, buf->tot_len, 0); debugf("DNS REQ for %s from %s:%d", getDomainNameWithoutWwwPrefix().c_str(), remoteIP.toString().c_str(), remotePort); _dnsHeader = (DNSHeader*) _buffer; if (_dnsHeader->QR == DNS_QR_QUERY && _dnsHeader->OPCode == DNS_OPCODE_QUERY && requestIncludesOnlyOneQuestion() && (_domainName == "*" || getDomainNameWithoutWwwPrefix() == _domainName) ) { char response[buf->tot_len+16]; int idx = buf->tot_len; _dnsHeader->QR = DNS_QR_RESPONSE; _dnsHeader->ANCount = _dnsHeader->QDCount; _dnsHeader->QDCount = _dnsHeader->QDCount; memcpy(response, _buffer, idx); //Set a pointer to the domain name in the question section response[idx] = 0xC0; response[idx+1] = 0x0C; //Type: "Host Address" response[idx+2] = 0x00; response[idx+3] = 0x01; //Set the response class to IN response[idx+4] = 0x00; response[idx+5] = 0x01; //TTL response[idx+6] = _ttl >> 24; response[idx+7] = _ttl >> 16; response[idx+8] = _ttl >> 8; response[idx+9] = _ttl; //RDATA length response[idx+10] = 0x00; response[idx+11] = 0x04; //4 byte IP address //The IP address response[idx+12] = _resolvedIP[0]; response[idx+13] = _resolvedIP[1]; response[idx+14] = _resolvedIP[2]; response[idx+15] = _resolvedIP[3]; sendTo(remoteIP, remotePort, response, idx+16); }
void IPAddressTest::testOperators() { IPAddress ip("10.0.0.51"); IPAddress mask(24, IPAddress::IPv4); IPAddress net = ip & mask; assert(net.toString() == "10.0.0.0"); IPAddress host("0.0.0.51"); assert((net | host) == ip); assert((~mask).toString() == "0.0.0.255"); }
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>().toString() << std::endl; IPAddress addr = ipIt->get<NetworkInterface::SUBNET_MASK>(); if (!addr.isWildcard()) std::cout << "Subnet: " << addr.toString() << " (/" << addr.prefixLength() << ")" << std::endl; addr = ipIt->get<NetworkInterface::BROADCAST_ADDRESS>(); if (!addr.isWildcard()) std::cout << "Broadcast: " << addr.toString() << std::endl; } std::cout << "=============" << std::endl << std::endl; } }
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 } }
IPAddress ESPSerialWiFiManager::_prompt_ip(String prompt, IPAddress def){ while(true){ String p(prompt); if(def != 0){ p = p + " (Default: " + def.toString() + ")"; } String ip_str = _prompt(p, ' ', 0); if(ip_str.length() == 0){ return def; } IPAddress ip; if(ip.fromString(ip_str)) return ip; else{ OFL("Invalid IP entered! Please try again.\n"); } } }
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); }
// 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; }
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); } }
void SocketDefaultImpl::capture(const IPAddress &addr, bool incoming) { SocketDebugger &debugger = SocketDebugger::instance(); if (!debugger.getCapture()) return; const string &dir = debugger.getCaptureDirectory(); SystemUtilities::ensureDirectory(dir); uint64_t id = debugger.getNextConnectionID(); string prefix = dir + "/" + String(id) + "-" + (incoming ? "in" : "out") + "-" + addr.toString() + "-"; #ifdef _WIN32 prefix = String::replace(prefix, ':', '-'); #endif string request = prefix + "request.dat"; string response = prefix + "response.dat"; in = SystemUtilities::open(incoming ? request : response, ios::out | ios::trunc); out = SystemUtilities::open(incoming ? response : request, ios::out | ios::trunc); }
void EthernetServer::begin(IPAddress address) { struct addrinfo hints, *servinfo, *p; int yes=1; int rv; char ipstr[INET_ADDRSTRLEN]; char portstr[6]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; sprintf(portstr, "%d", port); if ((rv = getaddrinfo(address.toString().c_str(), portstr, &hints, &servinfo)) != 0) { logError("getaddrinfo: %s\n", gai_strerror(rv)); return; } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { logError("socket: %s\n", strerror(errno)); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { logError("setsockopt: %s\n", strerror(errno)); freeaddrinfo(servinfo); return; } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); logError("bind: %s\n", strerror(errno)); continue; } break; } if (p == NULL) { logError("Failed to bind!\n"); freeaddrinfo(servinfo); return; } if (listen(sockfd, ETHERNETSERVER_BACKLOG) == -1) { logError("listen: %s\n", strerror(errno)); freeaddrinfo(servinfo); return; } freeaddrinfo(servinfo); fcntl(sockfd, F_SETFL, O_NONBLOCK); struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr; void *addr = &(ipv4->sin_addr); inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); logDebug("Listening for connections on %s:%s\n", ipstr, portstr); }
String getIP() { IPAddress ip = (WiFi.getMode() & WIFI_STA) ? WiFi.localIP() : WiFi.softAPIP(); return ip.toString(); }
void IPAddressTest::testBroadcast() { IPAddress broadcast = IPAddress::broadcast(); assert (broadcast.isBroadcast()); assert (broadcast.toString() == "255.255.255.255"); }
IPAddressBinding::IPAddressBinding(IPAddress ip) : invalid(false) { IPAddressBinding(ip.toString()); }
void got_IP(IPAddress ip, IPAddress netmask, IPAddress gateway) { Serial.printf("IP: %s\n", ip.toString().c_str()); //You can put here other job like web,tcp etc. }
int main(int argc, char** argv) { if (argc != 1) { Path p(argv[0]); std::cerr << "usage: " << p.getBaseName() << std::endl; return 1; } try { const NetworkInterface::Map map = NetworkInterface::map(); for ( NetworkInterface::Map::const_iterator it = map.begin(); it != map.end(); ++it) { const NetworkInterface& intf = it->second; std::string sep(""); std::cout << intf.name() << " [" << intf.index() << "]: "; std::cout << "<"; if (intf.isUp()) { std::cout << sep << "UP"; sep = ","; } if (intf.isRunning()) { std::cout << sep << "RUNNING"; sep = ","; } if (intf.isLoopback()) { std::cout << sep << "LOOPBACK"; sep = ","; } if (intf.isPointToPoint()) { std::cout << sep << "P2P"; sep = ","; } if (intf.supportsIPv4()) { std::cout << sep << "IPv4"; sep = ","; } if (intf.supportsIPv6()) { std::cout << sep << "IPv6"; sep = ","; } if (intf.supportsBroadcast()) { std::cout << sep << "BCAST"; sep = ","; } if (intf.supportsMulticast()) { std::cout << sep << "MCAST"; sep = ","; } if (!intf.isLoopback()) { std::cout << sep << std::dec << intf.mtu(); sep = ","; } std::cout << ">" << std::endl; const NetworkInterface::AddressList& ipList = intf.addressList(); NetworkInterface::AddressList::const_iterator ipIt = ipList.begin(); NetworkInterface::AddressList::const_iterator ipEnd = ipList.end(); for (; ipIt != ipEnd; ++ipIt) { std::cout << " " << ipIt->get<NetworkInterface::IP_ADDRESS>().toString(); IPAddress addr; addr = ipIt->get<NetworkInterface::SUBNET_MASK>(); if (!addr.isWildcard()) std::cout << '/' << addr.toString() << " (" << addr.prefixLength() << ')'; addr = ipIt->get<NetworkInterface::BROADCAST_ADDRESS>(); if (!addr.isWildcard()) std::cout << (intf.isPointToPoint() ? " dest " : " bcast ") << addr.toString(); std::cout << std::endl; } std::cout << std::endl; } } catch (Exception& exc) { std::cerr << exc.displayText() << std::endl; return 1; } return 0; }
/** * Configure access point * @param local_ip access point IP * @param gateway gateway IP * @param subnet subnet mask */ bool ESP8266WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet) { DEBUG_WIFI("[APConfig] local_ip: %s gateway: %s subnet: %s\n", local_ip.toString().c_str(), gateway.toString().c_str(), subnet.toString().c_str()); if(!WiFi.enableAP(true)) { // enable AP failed DEBUG_WIFI("[APConfig] enableAP failed!\n"); return false; } bool ret = true; struct ip_info info; info.ip.addr = static_cast<uint32_t>(local_ip); info.gw.addr = static_cast<uint32_t>(gateway); info.netmask.addr = static_cast<uint32_t>(subnet); if(!wifi_softap_dhcps_stop()) { DEBUG_WIFI("[APConfig] wifi_softap_dhcps_stop failed!\n"); } if(!wifi_set_ip_info(SOFTAP_IF, &info)) { DEBUG_WIFI("[APConfig] wifi_set_ip_info failed!\n"); ret = false; } struct dhcps_lease dhcp_lease; IPAddress ip = local_ip; ip[3] += 99; dhcp_lease.start_ip.addr = static_cast<uint32_t>(ip); DEBUG_WIFI("[APConfig] DHCP IP start: %s\n", ip.toString().c_str()); ip[3] += 100; dhcp_lease.end_ip.addr = static_cast<uint32_t>(ip); DEBUG_WIFI("[APConfig] DHCP IP end: %s\n", ip.toString().c_str()); if(!wifi_softap_set_dhcps_lease(&dhcp_lease)) { DEBUG_WIFI("[APConfig] wifi_set_ip_info failed!\n"); ret = false; } // set lease time to 720min --> 12h if(!wifi_softap_set_dhcps_lease_time(720)) { DEBUG_WIFI("[APConfig] wifi_softap_set_dhcps_lease_time failed!\n"); ret = false; } uint8 mode = 1; if(!wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &mode)) { DEBUG_WIFI("[APConfig] wifi_softap_set_dhcps_offer_option failed!\n"); ret = false; } if(!wifi_softap_dhcps_start()) { DEBUG_WIFI("[APConfig] wifi_softap_dhcps_start failed!\n"); ret = false; } // check config if(wifi_get_ip_info(SOFTAP_IF, &info)) { if(info.ip.addr == 0x00000000) { DEBUG_WIFI("[APConfig] IP config Invalid?!\n"); ret = false; } else if(local_ip != info.ip.addr) { ip = info.ip.addr; DEBUG_WIFI("[APConfig] IP config not set correct?! new IP: %s\n", ip.toString().c_str()); ret = false; } } else { DEBUG_WIFI("[APConfig] wifi_get_ip_info failed!\n"); ret = false; } return ret; }
void IPAddressTest::testWildcard() { IPAddress wildcard = IPAddress::wildcard(); assert (wildcard.isWildcard()); assert (wildcard.toString() == "0.0.0.0"); }