const char *GetTcpInfor(int peerfd)//get tcp information { static char infor[100] = ""; //store information SAI Peer = GetPeerAddr(peerfd);//get peerfd addr SAI Local = GetLocalAddr(peerfd);//get local addr snprintf(infor, sizeof infor, "%s:%d -> %s:%d", GetIp(&Local),//get ip GetPort(&Local), GetIp(&Peer),//get port GetPort(&Peer)); return infor; }
void main(int argc, char *argv[]) { int skt; int err, quit=0; int DataBytes; InitLib(); err=NetStart(); if(err<0) { Print("Init Ethernet error.\n\r"); return; } GetIp(MyIp); Print("IP=%d.%d.%d.%d\r\n", MyIp[0], MyIp[1], MyIp[2], MyIp[3]); skt=Nopen("*", "UDP/IP", 10000, 0, S_NOCON | S_NOWA); if(skt<0) { Print("Cannot open a connection for UDP/IP!"); Nterm(); return; } Print("Socket=%d\r\n", skt); SOCKET_NOBLOCK(skt); while(!quit) { YIELD(); // must add this line in the while loop DataBytes=Nread(skt, InBuf, 1500); if(DataBytes>0) { Print("%s\n\r",InBuf); memcpy(OutBuf, InBuf, DataBytes); Nwrite(skt, OutBuf, DataBytes); } if(Kbhit()) { switch(Getch()) { case 'q': case 'Q': quit=1; break; } } } Nclose(skt); Nterm(); }
void GetRouterLocal(char *dev) { struct ifreq ifr; int fd; fd = CreateSocket(PF_INET, SOCK_DGRAM, IPPROTO_IP); memcpy(ifr.ifr_name, dev, IFNAMSIZ); src_mac = GetMac(fd, dev); src_ip = GetIp(fd, dev); netmask = GetNetmask(fd, dev); router_ip = GetRouterIp(); broadcast = GetBroadcast(fd, dev); }
FString FInternetAddrX::ToString( bool bAppendPort ) const { uint32 Ip = 0; GetIp(Ip); // Get the individual bytes const int32 A = (Ip >> 24) & 0xFF; const int32 B = (Ip >> 16) & 0xFF; const int32 C = (Ip >> 8) & 0xFF; const int32 D = (Ip >> 0) & 0xFF; if (bAppendPort) { return FString::Printf(TEXT("%i.%i.%i.%i:%i"),A,B,C,D,GetPort()); } else { return FString::Printf(TEXT("%i.%i.%i.%i"),A,B,C,D); } }
AuthSession::AuthSession(QTcpSocket *socket) : SocketHandler(socket) { m_logout = false; m_accountId = 0; m_username = QString(); connect(m_socket, SIGNAL(disconnected()), this, SLOT(OnClose())); Log::Write(LOG_TYPE_INFO, "New incoming connection from %s", m_socket->peerAddress().toString().toLatin1().data()); QStringList ip = GetIp().split("."); WorldPacket data(SMSG_CLIENT_IP); for (quint8 i = 0; i < ip.size(); ++i) data << (quint8) ip.at(i).toUInt(); SendPacket(data); }
void BroadcastReceiver::WriteRecentEndpoints(const std::string& filename, uint8_t threshold) const { std::ofstream outFile; if(filename.compare("") == 0) outFile.open(mRecentFilename, std::ios::trunc); else outFile.open(filename, std::ios::trunc); if(!outFile.is_open()) { Trace(ZONE_ERROR, "Open file to write recent endpoints failed\n"); return; } // write to file for(auto it = mIpTable.begin(); it != mIpTable.end(); it++) { const auto currentEndpoint = it->second; if(currentEndpoint.GetScore() >= threshold) { //TODO refactor this but then we have to change the CLI implementation outFile << (int)(currentEndpoint.GetScore()) << ' ' << std::hex << currentEndpoint.GetIp() << ' ' << std::dec << currentEndpoint.GetPort() << ' ' << currentEndpoint.GetDeviceId() << '\n'; } } outFile.close(); }
bool UPnP::Create(u16 Port) { IUPnPNAT * Nat = NULL; IStaticPortMappingCollection * PortMappingCollection = NULL; IStaticPortMapping * PortMap = NULL; HRESULT Result; wchar_t Protocol[256]; wchar_t InternalClient[256]; wchar_t Description[256]; Destroy(); #ifdef MFC TRACE("UPnP: Adding port\n"); #endif if(!GetIp()) { return false; } size_t num_chars_converted{}; mbstowcs_s(&num_chars_converted, InternalClient, m_Address, 256); wcscpy_s(Protocol, L"UDP"); wcscpy_s(Description, L"Gunz"); // Create IUPnPNat Result = CoCreateInstance(CLSID_UPnPNAT, NULL, CLSCTX_INPROC_SERVER, IID_IUPnPNAT, (void **)&Nat); if(FAILED(Result)) { #ifdef MFC TRACE("UPnP: Unable to create UPnPNAT interface\n"); #endif return false; } Result = Nat->get_StaticPortMappingCollection(&PortMappingCollection); if(!PortMappingCollection || FAILED(Result)) { if(PortMappingCollection) PortMappingCollection->Release(); Nat->Release(); #ifdef MFC TRACE("UPnP: Unable to acquire a static portmapping collection\n"); #endif return false; } Result = PortMappingCollection->Add(Port, Protocol, Port, InternalClient, VARIANT_TRUE, Description, &PortMap); if(!PortMap || FAILED(Result)) { if(PortMap) PortMap->Release(); PortMappingCollection->Release(); Nat->Release(); #ifdef MFC TRACE("UPnP: Unable add port\n"); #endif return false; } #ifdef MFC TRACE("UPnP: Port %d forwarded to %s\n", Port, m_Address); #endif PortMap->Release(); PortMappingCollection->Release(); Nat->Release(); m_Port = Port; return true; }
// --- void VSWRtorsClsDebugInfoMessage::processARtor (const CMTYPOReference& rtor, VSWRtorAdmonAnswer&, const CMTYConfigurationDataPt& cfg, const CMTYLogSystemPt&, const VSWAdmonStatisticsPt&, const std::string& mssgId) { #ifdef __DEBUGSYSTEM __KEEPENTRYSIMPLETRACE #endif // A Message to the reproductors is going to be sent... // Then, the sender, is now this machine, and the port where the answer has to be sent back // its the port used by the reproductors to answer. // The user is the same. VSWRtorDefinition* rtorPt = (VSWRtorDefinition*) (rtor.object ()); CMTYGenericValueStr prms (std::string (__COMMANDDATACOLL__)); prms.add (_data.getStr (__PARAMETER0__)); prms.add (_data.getStr (__PARAMETER1__)); ToClsDInfoAReproductor clsDInfo (_sessionId, (mssgId == std::string (__NULL_STRING__)) ? generateId () : mssgId, CMTYIPDirection (GetIp ()), atoi (cfg -> valueForVariable (std::string (_SRVREPRODUCTORSPORT_)).c_str ()), prms); if (!clsDInfo.sendTo (rtorPt -> ip (), atoi (rtorPt -> port ().c_str ()))) { // If the conection isn't possible, // ...then a trace with info is kept into the system... #ifdef __DEBUGSYSTEM __CREATEDEBUGINFOADITIONALDATA (OD) __ADDDEBUGINFOADITIONALDATA ("IP", rtorPt -> ip (), OD) __KEEPTRACE (__ERRORDEBUGINFO ("Error (switching on / off class debug info) connecting with a reproductor", OD)) #endif } else setAnswersNeeded (answersNeeded () + 1); // The message was finally sent and then, an answer is needed... #ifdef __DEBUGSYSTEM __KEEPEXITSIMPLETRACE #endif }
bool WhitelistConfiguration::AddEntry(std::string entry) { vector<string> splitOnCommas; boost::split(splitOnCommas, entry, boost::is_any_of(",")); // Convert ip/xx notation if need be uint seperator = splitOnCommas.at(1).find("/"); if(seperator != string::npos) { if(GetSubnet(entry).size() > 0 && GetSubnet(entry).size() <= 2) { in_addr subnetmask; subnetmask.s_addr = 0; int oldMask = atoi(GetSubnet(entry).c_str()); for(int i = 0; i < oldMask; i++) { subnetmask.s_addr |= subnetmask.s_addr | (1 << i); } char *newSubnet = inet_ntoa(subnetmask); entry = GetInterface(entry) + "," + GetIp(entry) + "/" + string(newSubnet); } } ifstream ipListFileStream(Config::Inst()->GetPathWhitelistFile()); stringstream ipListNew; bool alreadyExists = false; if(ipListFileStream.is_open()) { while(ipListFileStream.good()) { string line; if(getline (ipListFileStream,line) == 0) { continue; } if(line == entry) { alreadyExists = true; break; } else { ipListNew << line << endl; } } ipListFileStream.close(); } else { LOG(ERROR,"Unable to open file: " + Config::Inst()->GetPathWhitelistFile(), ""); return false; } if(!alreadyExists) { ofstream whitelist(Config::Inst()->GetPathWhitelistFile()); if(whitelist.is_open()) { whitelist << ipListNew.str(); whitelist << entry; whitelist.close(); } else { LOG(ERROR,"Unable to open file: " + Config::Inst()->GetPathWhitelistFile(), ""); return false; } } return true; }
void SysWork(char *addr, int trc) { int i=1,end=0,chk; u_char *src; //печать адресов на экран char my_ip[16]; //для хранения своего адреса struct sniff_icmp *icmp,*icmprep; //заголовки struct sniff_ip *ip,*iprep; struct sockaddr_in sr_addr; //адрес, до котоого пингуем socklen_t len=sizeof(struct sockaddr_in); u_char buf[sizeof(struct sniff_icmp)+sizeof(struct sniff_ip)], recbuf[sizeof(struct sniff_icmp)+sizeof(struct sniff_ip)]; //----------------первоначальная настройка------------------- atexit(EndSys); GetIp("eth0",my_ip); //забираем свой адрес //пивязываем заголовк к памяти ip=(struct sniff_ip*)buf; icmp=(struct sniff_icmp*)(buf+sizeof(struct sniff_ip)); iprep=(struct sniff_ip*)recbuf; icmprep=(struct sniff_icmp*)(recbuf+sizeof(struct sniff_ip)); //заполнение заголовка ip ip->ihl=5; ip->ver=4; ip->tos=0; ip->len=sizeof(struct sniff_icmp)+sizeof(struct sniff_ip); ip->id=htons(7777); ip->frag_off=0; if(trc==1) ip->ttl=1; else ip->ttl=128; ip->protocol=IPPROTO_ICMP; ip->ip_dest=inet_addr(addr); ip->ip_source=inet_addr(my_ip); ip->cs=0; //заполнение заголовка icmp icmp->type=8; icmp->code=0; icmp->un.echo.id=0; icmp->un.echo.sequence=0; icmp->cs=0; icmp->cs=CheckSum((unsigned short*)icmp,sizeof(struct sniff_icmp)); ip->cs=CheckSum((unsigned short*)ip,sizeof(struct sniff_ip)); //заполнение адреса sr_addr.sin_addr.s_addr=inet_addr(addr); sr_addr.sin_family=AF_INET; //открываем сокет rid=socket(AF_INET,SOCK_RAW,IPPROTO_ICMP); if(rid<0) { ErrSys("socket create\n"); } //не заполнять заголовки автоматически chk=setsockopt(rid,IPPROTO_IP,IP_HDRINCL,&i,sizeof(i)); if(chk<0) ErrSys("setsockopt\n"); //------------------основная работа------------------- //trace if(trc==1) { puts("tracing..."); do { //отправляем chk=sendto(rid,buf,sizeof(struct sniff_icmp)+sizeof(struct sniff_ip),0, (struct sockaddr*)&sr_addr,len); if(chk<0) ErrSys("send\n"); //ждем ответа chk=recvfrom(rid,recbuf,sizeof(struct sniff_icmp)+sizeof(struct sniff_ip),0, (struct sockaddr*)&sr_addr,&len); if(chk<0) ErrSys("recv\n"); else { src=(u_char*)&iprep->ip_source; printf("%d host: %d.%d.%d.%d, ttl: %d\n",i++,src[0],src[1],src[2],src[3], iprep->ttl); //меняем ттл пересчитываем контольную сумму ip->ttl++; ip->cs=0; ip->cs=CheckSum((unsigned short*)ip,sizeof(struct sniff_ip)); } } //продолжаем, пока не получим ответ от искомого адреса while(ip->ip_dest!=iprep->ip_source); } //ping else { while(end!=4) { //отправляем chk=sendto(rid,buf,sizeof(struct sniff_icmp)+sizeof(struct sniff_ip),0, (struct sockaddr*)&sr_addr,len); if(chk<0) ErrSys("send\n"); printf("ping sent\n"); //ждем ответа chk=recvfrom(rid,recbuf,sizeof(struct sniff_icmp)+sizeof(struct sniff_ip),0, (struct sockaddr*)&sr_addr,&len); if(chk<0) ErrSys("recv\n"); else { src=(u_char*)&iprep->ip_source; printf("from %d.%d.%d.%d, ttl: %d\n",src[0],src[1],src[2],src[3],iprep->ttl); //printf("icmp type %x code %x\n",icmprep->type,icmp->code); } usleep(200000); end++; } } }