public static async Task<IPHostEntry> ResolveDNS(string remoteHostName) { if (string.IsNullOrEmpty(remoteHostName)) return null; IPHostEntry result = new IPHostEntry(); try { IReadOnlyList<EndpointPair> data = await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0"); if (data != null && data.Count > 0) { result.AddressList = new IPAddress[data.Count]; int i = 0; foreach (EndpointPair item in data) { if (item != null && item.RemoteHostName != null && item.RemoteHostName.Type == HostNameType.Ipv4) { result.AddressList[i] = IPAddress.Parse(item.RemoteHostName.CanonicalName); } i++; } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("error resolving dns name {0}. ex:\n{1}", remoteHostName, ex); return null; } return result; }
//public ConcurrentDictionary<string, ServerListing> Servers //{ // get { return servers; } //} private ConcurrentDictionary<string, ServerListing> servers = new ConcurrentDictionary<string, ServerListing>(); #endregion public void Query(string[] metaservers = null) { l.Info("[META] Querying metaservers."); if (metaservers == null) { metaservers = DefaultMetaservers; } foreach (var metaserver in DefaultMetaservers) { IPHostEntry host = Dns.GetHostEntry(metaserver); if (host == null) { l.Error("Host DNS lookup failed for metaserver: " + metaserver); continue; } Socket socket = null; try { try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP); socket.Connect(host.AddressList, NetConstants.MetaserverPort); } catch (Exception ex) { l.Warn("Failed to connect to: " + host.HostName + ". Exception: " + ex.ToString()); continue; } if (!socket.Connected) { socket.Dispose(); continue; } byte[] sendBytes = ASCIIEncoding.ASCII.GetBytes("?version=_"); try { socket.Send(sendBytes); } catch (Exception ex) { l.Warn("Error sending to metaserver '" + metaserver + "': " + ex.ToString()); continue; } int packetsReceived = 0; receive: if (packetsReceived > 1) { l.Trace("packetsReceived > 1"); } byte[] recvBuffer = new byte[8192]; int bytesRead = 0; try { if (packetsReceived == 0 || socket.Poll(250, SelectMode.SelectRead)) { socket.ReceiveTimeout = 5000; // HARDTIME TIMEOUT bytesRead = socket.Receive(recvBuffer); } } catch (Exception ex) { l.Warn("Error receiving from metaserver: " + ex.ToString()); continue; } if (bytesRead == 0) { if (packetsReceived == 0) { l.Warn("Received nothing from metaserver'" + metaserver + "'"); } continue; } packetsReceived++; string result = ASCIIEncoding.ASCII.GetString(recvBuffer); string[] lines = result.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); int lineCount = 0; string protocolType = null; string protocolUnknown2; foreach (var line in lines) { if (line.StartsWith(((char)0).ToString())) { break; } string[] cells = line.Split(','); if (lineCount++ == 0) { protocolType = cells[0]; if (protocolType.Equals("r")) { protocolUnknown2 = cells[1]; } continue; } ServerListing listing = null; if (protocolType.Equals("r")) { listing = new ServerListing(cells[0]); listing.Source = protocolType; listing.Port = Convert.ToInt32(cells[1]); listing.Status = cells[2]; listing.Age = Convert.ToInt32(cells[3]); listing.Players = Convert.ToInt32(cells[4]); listing.Queue = Convert.ToInt32(cells[5]); listing.Type = cells[6]; listing.Comment = String.Empty; } else if (protocolType.Equals("s")) { listing = new ServerListing(cells[0]); listing.Source = protocolType; listing.Type = cells[1]; listing.Comment = cells[2]; listing.Port = Convert.ToInt32(cells[4]); listing.Players = Convert.ToInt32(cells[5]); listing.Queue = Convert.ToInt32(cells[6].Trim()); listing.Status = "2"; // TODO REVIEW if (listing.Type.Equals("unknown")) { listing.Status = "3"; // TODO REVIEW } listing.Age = 0; } else { l.Warn("Unknown metaserver protocol: " + protocolType); } if (listing != null && listing.IsSupported) { l.Debug("[meta] " + listing.ToString()); if (ServerListings.Contains(listing)) { ServerListings.Remove(listing); } ServerListings.Add(listing); servers.Set(listing.Key, listing); } } goto receive; } finally { try { if (socket != null) { socket.Dispose(); socket = null; } } catch (Exception ex) { l.Trace(ex.ToString()); } } } }
public void ClientServiceLoop() { try { IPHostEntry ipHostInfo = Dns.GetHostEntry(remote_addr); IPAddress ipAddress; IPEndPoint ipepRemote = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 100); if (remote_addr == "127.0.0.1") { ipepRemote = new IPEndPoint(IPAddress.Parse(remote_addr), int.Parse(remote_port)); } else { ipAddress = ipHostInfo.AddressList[0]; ipepRemote = new IPEndPoint(ipAddress, int.Parse(remote_port)); } byte[] buffer = new byte[2048]; int count = 0; string text = ""; ASCIIEncoding buf = new ASCIIEncoding(); text = "DXClusterClient - Connecting to " + remote_addr.ToString(); buf.GetBytes(text, 0, text.Length, buffer, 0); ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); ClusterClient.Connect(ipepRemote); if (ClusterClient.Connected) { sw = ClusterClient.GetStream(); sr = ClusterClient.GetStream(); text = "DXClusterClient - Connected to " + remote_addr.ToString(); buf.GetBytes(text, 0, text.Length, buffer, 0); ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); } while (ClusterClient.Connected) { count = sr.Read(buffer, 0, 2048); if (count == 0) { ClusterClient.Close(); } else { ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 0, buffer, count); } } text = "DXClusterClient - Disconnected"; buf = new ASCIIEncoding(); buf.GetBytes(text, 0, text.Length, buffer, 0); ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); ClusterClient.Close(); } catch (Exception ex) { Debug.Write(ex.ToString()); byte[] buffer = new byte[100]; string text = "DXClusterClient - Disconnected"; ASCIIEncoding buf = new ASCIIEncoding(); buf.GetBytes(text, 0, text.Length, buffer, 0); try { ClusterForm.Invoke(new CrossThreadCallback(ClusterForm.CrossThreadCommand), 1, buffer, text.Length); } catch { } } }
public static IPAddress _QueryDns(string host, string dns_servers, bool IPv6_first = false) { IPAddress ret_ipAddress = null; { if (!string.IsNullOrEmpty(dns_servers)) { OpenDNS.Types[] types; if (IPv6_first) { types = new Types[] { Types.AAAA, Types.A } } ; else { types = new Types[] { Types.A, Types.AAAA } }; string[] _dns_server = dns_servers.Split(','); List <IPEndPoint> dns_server = new List <IPEndPoint>(); List <IPEndPoint> local_dns_server = new List <IPEndPoint>(); foreach (string server_str in _dns_server) { IPAddress ipAddress = null; string server = server_str.Trim(' '); int index = server.IndexOf(':'); string ip = null; string port = null; if (index >= 0) { if (server.StartsWith("[")) { int ipv6_end = server.IndexOf(']', 1); if (ipv6_end >= 0) { ip = server.Substring(1, ipv6_end - 1); index = server.IndexOf(':', ipv6_end); if (index == ipv6_end + 1) { port = server.Substring(index + 1); } } } else { ip = server.Substring(0, index); port = server.Substring(index + 1); } } else { index = server.IndexOf(' '); if (index >= 0) { ip = server.Substring(0, index); port = server.Substring(index + 1); } else { ip = server; } } if (ip != null && IPAddress.TryParse(ip, out ipAddress)) { int i_port = 53; if (port != null) { int.TryParse(port, out i_port); } dns_server.Add(new IPEndPoint(ipAddress, i_port)); //dns_server.Add(port == null ? ip : ip + " " + port); } } for (int query_i = 0; query_i < types.Length; ++query_i) { DnsQuery dns = new DnsQuery(host, types[query_i]); dns.RecursionDesired = true; foreach (IPEndPoint server in dns_server) { dns.Servers.Add(server); } if (dns.Send()) { int count = dns.Response.Answers.Count; if (count > 0) { for (int i = 0; i < count; ++i) { if (((ResourceRecord)dns.Response.Answers[i]).Type != types[query_i]) { continue; } return(((OpenDNS.Address)dns.Response.Answers[i]).IP); } } } } } { try { GetHostEntryHandler callback = new GetHostEntryHandler(Dns.GetHostEntry); IAsyncResult result = callback.BeginInvoke(host, null, null); if (result.AsyncWaitHandle.WaitOne(10000, true)) { IPHostEntry ipHostEntry = callback.EndInvoke(result); foreach (IPAddress ad in ipHostEntry.AddressList) { if (ad.AddressFamily == AddressFamily.InterNetwork) { return(ad); } } foreach (IPAddress ad in ipHostEntry.AddressList) { return(ad); } } } catch { } } } return(ret_ipAddress); }
LoginResponseData HandleLogin(string firstName, string lastName, string password, string start, string version, string channel) { LoginResponseData response = new LoginResponseData(); Agent agent; UUID agentID = Authentication.Authenticate(firstName, lastName, password); if (agentID != UUID.Zero) { // Authentication successful, create a login instance of this agent agent = Accounts.CreateInstance(agentID); if (agent != null) { // Assign a circuit code and insert the agent into the unassociatedAgents dictionary agent.CircuitCode = UDP.CreateCircuit(agent); agent.TickLastPacketReceived = Environment.TickCount; agent.LastLoginTime = Utils.DateTimeToUnixTime(DateTime.Now); // Get this machine's IP address IPHostEntry addresses = Dns.GetHostByName(Dns.GetHostName()); IPAddress simIP = addresses.AddressList.Length > 0 ? addresses.AddressList[0] : IPAddress.Loopback; response.AgentID = agent.AgentID; response.SecureSessionID = agent.SecureSessionID; response.SessionID = agent.SessionID; response.CircuitCode = agent.CircuitCode; response.AgentAccess = agent.AccessLevel; response.BuddyList = null; // FIXME: response.FirstName = agent.FirstName; response.HomeLookAt = agent.HomeLookAt; response.HomePosition = agent.HomePosition; response.HomeRegion = agent.HomeRegionHandle; response.InventoryRoot = agent.InventoryRoot; response.InventorySkeleton = null; // FIXME: response.LastName = agent.LastName; response.LibraryOwner = agent.InventoryLibraryOwner; response.LibraryRoot = agent.InventoryLibraryRoot; response.LibrarySkeleton = null; // FIXME: response.LookAt = agent.CurrentLookAt; response.Message = "Welcome to Simian"; response.Reason = String.Empty; uint regionX, regionY; Utils.LongToUInts(agent.CurrentRegionHandle, out regionX, out regionY); response.RegionX = regionX; response.RegionY = regionY; response.SecondsSinceEpoch = DateTime.Now; // FIXME: Actually generate a seed capability response.SeedCapability = String.Format("http://{0}:{1}/seed_caps", simIP, HttpPort); response.SimIP = simIP; response.SimPort = (ushort)UDPPort; response.StartLocation = "last"; // FIXME: response.Success = true; } else { // Something went wrong creating an agent instance, return a fail response response.AgentID = agentID; response.FirstName = firstName; response.LastName = lastName; response.Message = "Failed to create an account instance"; response.Reason = "account"; response.Success = false; } } else { // Authentication failed, return a fail response response.AgentID = agentID; response.FirstName = firstName; response.LastName = lastName; response.Message = "Authentication failed"; response.Reason = "key"; response.Success = false; } return(response); }
protected PingTaskBase(PingExecutor executor, IPHostEntry host) : this(executor) { _host = host; }
//var ip = HttpContext.Request.Host; // var remoteIpAddress = Request.Host.Host; public static string GetIPClient() { IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName()); return(heserver.AddressList.ToList().Where(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault().ToString()); }
public static string GetIpAddress(string hostname) { IPHostEntry hostEntry = Dns.GetHostEntry(hostname); return(hostEntry.AddressList[0].ToString()); }
private static void ExecuteRequest(object arg) { try { using (Socket myClient = (Socket)arg) { if (myClient.Connected) { byte[] httpRequest = ReadToEnd(myClient); Parser http = new Parser(httpRequest); if (http.Items == null || http.Items.Count <= 0 || !http.Items.ContainsKey("Host")) { WriteLog("REQUEST {0} bytes, headers not found.", httpRequest.Length); } else { WriteLog("REQUEST {0} bytes, method{1}, host {2}:{3}", httpRequest.Length, http.Method, http.Host, http.Port); // WriteLog(http.GetHeadersAsString()); byte[] response = null; if (_NeedAuth) { if (!http.Items.ContainsKey("Authorization")) { response = GetHTTPError(401, "Unauthorized"); myClient.Send(response, response.Length, SocketFlags.None); return; } else { string auth = Encoding.UTF8.GetString(Convert.FromBase64String(http.Items["Authorization"].Source.Replace("Basic ", ""))); string login = auth.Split(":".ToCharArray())[0]; string pwd = auth.Split(":".ToCharArray())[1]; if (_Login != login || _Password != pwd) { // wrong login or password response = GetHTTPError(401, "Unauthorized"); myClient.Send(response, response.Length, SocketFlags.None); return; } } } //check blacklist if (_AllowBlackList && _BlackList != null && Array.IndexOf(_BlackList, http.Host.ToLower()) != -1) { response = GetHTTPError(403, "Forbidden"); myClient.Send(response, response.Length, SocketFlags.None); return; } bool ready = false; if (UseCache) { if (Cache.HasResource(http.Path)) { ready = true; response = Cache.GetData(http.Path); if (response != null) { myClient.Send(response, response.Length, SocketFlags.None); } } } if (!ready) { IPHostEntry myIPHostEntry = Dns.GetHostEntry(http.Host); if (myIPHostEntry == null || myIPHostEntry.AddressList == null || myIPHostEntry.AddressList.Length <= 0) { WriteLog("Can't determine IP-adress by host {0}.", http.Host); } else { IPEndPoint myIPEndPoint = new IPEndPoint(myIPHostEntry.AddressList[0], http.Port); if (http.Method == Parser.MethodsList.CONNECT) { WriteLog("Protocol HTTPS not impemented."); response = GetHTTPError(501, "Not Implemented"); } // HTTP.Parser.MethodsList.CONNECT else { //if (!ready) { //redirect using (Socket myRerouting = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { myRerouting.Connect(myIPEndPoint); if (myRerouting.Send(httpRequest, httpRequest.Length, SocketFlags.None) != httpRequest.Length) { WriteLog("Data to host {0} was not sended...", http.Host); } else { //getting answer Parser httpResponse = new Parser(ReadToEnd(myRerouting)); if (httpResponse.Source != null && httpResponse.Source.Length > 0) { WriteLog("Request recieved {0} bytes, status code {1}", httpResponse.Source.Length, httpResponse.StatusCode); // WriteLog(httpResponse.GetHeadersAsString()); response = httpResponse.Source; switch (httpResponse.StatusCode) { case 400: case 403: case 404: case 407: case 500: case 501: case 502: case 503: response = GetHTTPError(httpResponse.StatusCode, httpResponse.StatusMessage); break; default: if (_AppendHtml) { //check if html if (httpResponse.Items.ContainsKey("Content-Type") && ((ItemContentType)httpResponse.Items["Content-Type"]).Value == "text/html") { //get body string body = httpResponse.GetBodyAsString(); body = Regex.Replace(body, "<title>(?<title>.*?)</title>", "<title>ProxyServer - $1</title>"); body = Regex.Replace(body, "(<body.*?>)", "$1<div style='height:20px;width:100%;background-color:black;color:white;font-weight:bold;text-align:center;'>Example of Proxy Server</div>"); httpResponse.SetStringBody(body); response = httpResponse.Source; } } //you can change image data too break; } } else { WriteLog("Recieved answer 0 byte"); } } myRerouting.Close(); } } // HTTP.Parser.MethodsList.CONNECT if (AllowStoreInCache) { Cache.SetData(http.Path, response); } } if (response != null) { myClient.Send(response, response.Length, SocketFlags.None); } } } } myClient.Close(); } } } catch (Exception ex) { WriteLog("Error: ", ex.Message); } }
public string lista(string operacion, String nombre, string apellido, int edad) { string cadena = operacion + nombre.ToString() + "," + apellido.ToString() + "," + edad.ToString(); // Declara un bufer de datos para recibir datos . byte[] bytes = new byte[1024]; // Se conecta al dispositivo remoto . try { // Establece un punto remoto final para el socket. // Este ejemplo usa el puerto 11000 en la computadora local. IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; // IPEndPopPnt remoteEP = new IPEndPoint(ipAddrPAdress.Paress, 11000); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // Crear un socket TCP/IP . Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Conetarse al punto final remoto captura cualquier error . try { sender.Connect(remoteEP); sender.RemoteEndPoint.ToString(); // codifica datos en un string dentro de un arreglo de bits. byte[] msg = Encoding.ASCII.GetBytes(cadena); // Envia datos a traves del socket . int bytesSent = sender.Send(msg); // Recibe ladespuesta desde el dispositivo remoto . int bytesRec = sender.Receive(bytes); string respuesta = (Encoding.ASCII.GetString(bytes, 0, bytesRec)); // libera el socket. sender.Shutdown(SocketShutdown.Both); sender.Close(); return(respuesta); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Error no manejado : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } return("no valido"); }
public void SendFinalMessage(int messageNo, int myPriority) { try { // Find the IP address of localhost IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = null; foreach (IPAddress ip in ipHostInfo.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { ipAddress = ip; break; } } IPEndPoint remoteEP = new IPEndPoint(ipAddress, 1081); Socket sendSocket; try { // Create a TCP/IP socket. sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the Network sendSocket.Connect(remoteEP); // Generate and encode the multicast message into a byte array. // I removed the first space in this message //message looks like: Final.1.2.10.<EOM> string message = "Final." + myID + "." + messageNo + "." + myPriority + ".<EOM>\n"; byte[] msg = Encoding.ASCII.GetBytes(message); //SentBoxAppend(message); // Send the data to the network. int bytesSent = sendSocket.Send(msg); sendSocket.Shutdown(SocketShutdown.Both); sendSocket.Close(); //Console.WriteLine("Press ENTER to terminate ..."); //Console.ReadLine(); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
// This method sets up a socket for receiving messages from the Network private async void ReceiveMulticast() { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; // Determine the IP address of localhost IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = null; foreach (IPAddress ip in ipHostInfo.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { ipAddress = ip; break; } } IPEndPoint localEndPoint = new IPEndPoint(ipAddress, myPort); // Create a TCP/IP socket for receiving message from the Network. TcpListener listener = new TcpListener(localEndPoint); listener.Start(88); try { string data = null; // Start listening for connections. while (true) { //Console.WriteLine("Waiting for a connection..."); // Program is suspended while waiting for an incoming connection. TcpClient tcpClient = await listener.AcceptTcpClientAsync(); //Console.WriteLine("connectted"); data = null; // Receive one message from the network while (true) { bytes = new byte[1024]; NetworkStream readStream = tcpClient.GetStream(); int bytesRec = await readStream.ReadAsync(bytes, 0, 1024); data += Encoding.ASCII.GetString(bytes, 0, bytesRec); // All messages ends with "<EOM>" // Check whether a complete message has been received if (data.IndexOf("<EOM>") > -1) { break; } } //***** the data is received, select the type of the data. char preamble = data[0]; switch (preamble) { case 'M': // a typical message is like: "Msg #3 from Middleware3:[7]<EOM>\n" // retrive sender id and such string keyword = "Middleware"; int senderPositionInMsg = data.IndexOf(keyword) + keyword.Length; int columPosition = data.IndexOf(":"); string senderStr = data.Substring(senderPositionInMsg, columPosition - senderPositionInMsg); int AtPosition = data.IndexOf("["); int EndPosition = data.IndexOf("]"); int hashPosition = data.IndexOf("#"); int fromPosition = data.IndexOf("from"); string restOfString = data.Substring(hashPosition + 1, fromPosition - hashPosition - 1); string MsgStamp = data.Substring(AtPosition + 1, EndPosition - AtPosition - 1); int sender = Int32.Parse(senderStr); //the sender id int msgTS = Int32.Parse(MsgStamp); int senderMsgNo = Int32.Parse(restOfString); //the no of msg from a particular sender priority = Math.Max(priority + 1, msgTS); TotalOrderMessage currentMsg = new TotalOrderMessage(data, sender, senderMsgNo, priority); holdingQ.Add(currentMsg); ReceivedBoxAppend(data); //*** send proposed message SendProposedMessage(sender, senderMsgNo, priority); break; //msessage looks like: Proposed receiver sender msgno priority <EOM> case 'P': string[] tokensP = data.Split('.'); if (Int32.Parse(tokensP[2]) == myID) { //ReceivedBoxAppend(data); //int receiver = Int32.Parse(tokens[1]); int thisMsgNo = Int32.Parse(tokensP[3]); int thisPrio = Int32.Parse(tokensP[4]); proposedInfo[thisMsgNo].Add(thisPrio); bool porposedFinished = false; if (proposedInfo[thisMsgNo].Count == 5) { proposedInfo[thisMsgNo].Sort(); int maxPriority = proposedInfo[thisMsgNo].Last(); //send final SendFinalMessage(thisMsgNo, maxPriority); clock = Math.Max(clock, maxPriority); porposedFinished = true; } if (porposedFinished) { proposedInfo.Remove(thisMsgNo); } } break; //msessage looks like: final sender msgno priority <EOM> case 'F': //ReceivedBoxAppend(data); string[] tokensF = data.Split('.'); int finalSender = Int32.Parse(tokensF[1]); int finalMsgNo = Int32.Parse(tokensF[2]); int finalPrio = Int32.Parse(tokensF[3]); //TotalOrderMessage tom = holdingQ.Find(x => ()); bool succeed = SetMessagePriorityInQueue(finalSender, finalMsgNo, finalPrio); if (!succeed) { Console.WriteLine("Error, cant find a final message in queue"); return; } holdingQ = sortHoldingQueue(holdingQ); //if ((holdingQ.First().senderId != finalSender || holdingQ.First().senderMsgNo != finalMsgNo) && holdingQ.First().deliverable == true) // Console.WriteLine("assertion failed"); /*if (holdingQ.First().senderId == finalSender && holdingQ.First().senderMsgNo == finalMsgNo) * { * TotalOrderMessage tommy = holdingQ.First(); * ReadyBoxAppend(tommy); * deliveryQ.Add(tommy); * holdingQ.Remove(tommy); * clock = Math.Max(tommy.timeStamp, clock) + 1; * while (holdingQ.Count > 0 && holdingQ.First().deliverable == true) * { * TotalOrderMessage jerry = holdingQ.First(); * ReadyBoxAppend(jerry); * deliveryQ.Add(jerry); * holdingQ.Remove(jerry); * clock = Math.Max(jerry.timeStamp, clock) + 1; * } * }*/ while (holdingQ.Count > 0 && holdingQ.First().deliverable == true) { TotalOrderMessage jerry = holdingQ.First(); ReadyBoxAppend(jerry); deliveryQ.Add(jerry); holdingQ.Remove(jerry); clock = Math.Max(jerry.timeStamp, clock) + 1; } break; } string display = "["; display += clock; textBox1.Text = display + "]"; } } catch (Exception ee) { Console.WriteLine(ee.ToString()); } }
public static PortDefinition[] EnumeratePorts( System.Net.IPAddress DiscoveryMulticastAddress, System.Net.IPAddress DiscoveryMulticastAddressRecv, int DiscoveryMulticastPort, string DiscoveryMulticastToken, int DiscoveryMulticastTimeout, int DiscoveryTTL ) { PortDefinition_Tcp [] ports = null; Dictionary <string, string> addresses = new Dictionary <string, string>(); try { IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in hostEntry.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { int cnt = 0; int total = 0; byte[] data = new byte[1024]; Socket sock = null; Socket recv = null; System.Net.IPEndPoint endPoint = new System.Net.IPEndPoint(ip, 0); System.Net.EndPoint epRemote = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 26001); System.Net.IPEndPoint epRecv = new System.Net.IPEndPoint(ip, DiscoveryMulticastPort); System.Net.IPEndPoint epMulticast = new System.Net.IPEndPoint(DiscoveryMulticastAddress, DiscoveryMulticastPort); try { sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); recv = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); recv.Bind(epRecv); recv.ReceiveTimeout = DiscoveryMulticastTimeout; recv.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(DiscoveryMulticastAddressRecv, ip)); sock.Bind(endPoint); sock.MulticastLoopback = false; sock.Ttl = (short)DiscoveryTTL; sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 64); // send ping sock.SendTo(System.Text.Encoding.ASCII.GetBytes(DiscoveryMulticastToken), SocketFlags.None, epMulticast); while (0 < (cnt = recv.ReceiveFrom(data, total, data.Length - total, SocketFlags.None, ref epRemote))) { addresses[((IPEndPoint)epRemote).Address.ToString()] = ""; total += cnt; recv.ReceiveTimeout = DiscoveryMulticastTimeout / 2; } recv.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new MulticastOption(DiscoveryMulticastAddressRecv)); } // SocketException occurs in RecieveFrom if there is no data. catch (SocketException) { } finally { if (recv != null) { recv.Close(); recv = null; } if (sock != null) { sock.Close(); sock = null; } } // use this if we need to get the MAC address of the device SOCK_discoveryinfo disc = new SOCK_discoveryinfo(); disc.ipaddr = 0; disc.macAddressLen = 0; int idx = 0; int c_DiscSize = Marshal.SizeOf(disc); while (total >= c_DiscSize) { byte[] discData = new byte[c_DiscSize]; Array.Copy(data, idx, discData, 0, c_DiscSize); GCHandle gch = GCHandle.Alloc(discData, GCHandleType.Pinned); disc = (SOCK_discoveryinfo)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(SOCK_discoveryinfo)); gch.Free(); // previously we only displayed the IP address for the device, which doesn't // really tell you which device you are talking to. The MAC address should be unique. // therefore we will display the MAC address in the device display name to help distinguish // the devices. if (disc.macAddressLen <= 64 && disc.macAddressLen > 0) { IPAddress ipResp = new IPAddress((long)disc.ipaddr); // only append the MAC if it matches one of the IP address we got responses from if (addresses.ContainsKey(ipResp.ToString())) { string strMac = ""; for (int mi = 0; mi < disc.macAddressLen - 1; mi++) { unsafe { strMac += string.Format("{0:x02}-", disc.macAddressBuffer[mi]); } } unsafe { strMac += string.Format("{0:x02}", disc.macAddressBuffer[disc.macAddressLen - 1]); } addresses[ipResp.ToString()] = strMac; } } total -= c_DiscSize; idx += c_DiscSize; } } } } catch (Exception e2) { System.Diagnostics.Debug.Print(e2.ToString()); } ports = new PortDefinition_Tcp[addresses.Count]; int i = 0; foreach (string key in addresses.Keys) { ports[i++] = new PortDefinition_Tcp(IPAddress.Parse(key), addresses[key]); } return(ports); }
public bool BindSocket() { try { IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; //IPEndPoint localEndPoint = new IPEndPoint(ipAddress, _protocolPort); // Get from hostname IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("172.16.21.50"), _protocolPort); // Static Socket listener = new Socket( ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndPoint); } catch (ArgumentNullException argNullE) { //Console.WriteLine($"Socket Listener Connect Exception : LocalEndPoint was null."); throw argNullE; } catch (SocketException socE) { throw socE; //Console.WriteLine($"Socket Listener Connect Exception : An error occurred when attempting to access the socket."); } catch (ObjectDisposedException objDisE) { throw objDisE; //Console.WriteLine($"Socket Listener Connect Exception : Socket has been closed."); } catch (SecurityException secE) { throw secE; //Console.WriteLine($"Socket Listener Connect Exception : A caller higher in the call stack does not have permission for the requested operation."); } catch (Exception e) { //Console.WriteLine($"Socket Listener Connect Exception : Something blocked the socket bind."); return(false); throw e; } try { listener.Listen(10); } catch (SocketException socE) { throw socE; //Console.WriteLine($"Socket Listener Connect Exception : An error occurred when attempting to access the socket."); } catch (ObjectDisposedException objDisE) { throw objDisE; //Console.WriteLine($"Socket Listener Connect Exception : Socket has been closed."); } catch (Exception e) { //Console.WriteLine($"Socket Listener Connect Exception"); return(false); throw e; } _socket = listener; return(true); } catch (Exception e) { //Console.WriteLine($"Socket Listener Connect Exception : Something went completely wrong."); return(false); throw e; } }
internal async Task<IPHostEntry> GetHostEntryAsync() { string uriHost; lock (hostE) { if (host != null) return host; uriHost = uri.Host; // There is no need to do DNS resolution on literal IP addresses if (uri.HostNameType == UriHostNameType.IPv6 || uri.HostNameType == UriHostNameType.IPv4) { if (uri.HostNameType == UriHostNameType.IPv6) { // Remove square brackets uriHost = uriHost.Substring(1, uriHost.Length - 2); } // Creates IPHostEntry host = new IPHostEntry { AddressList = new[] { IPAddress.Parse(uriHost) } }; return host; } } // Try DNS resolution on host names NameResolutionResult dnsResult; try { dnsResult = await DnsResolver.ResolveHostNameAsync(uriHost).ConfigureAwait(false); if (NetworkError.Success != dnsResult.NetworkErrorCode) return null; } catch { return null; } var ipHostEntry = new IPHostEntry { AddressList = dnsResult.IPEndPoints .Select(ep => ep.Address) .ToArray() }; lock (hostE) { if (!ReferenceEquals(uriHost, uri.Host)) return null; host = ipHostEntry; } return host; }
/// ----------------------------------------------------------------------------- /// <summary> /// Method which will begin a socket connection to specified host on specified port /// </summary> /// <param name="remotehost">Host to connect to</param> /// <param name="remoteport">Port to connect to</param> /// <remarks> /// </remarks> /// <history> /// [Caleb] 6/18/2005 Created /// </history> /// ----------------------------------------------------------------------------- public void Connect(string remotehost, int remoteport) { try { Socket obj_Socket = m_tmpSocket; if (obj_Socket.Connected == false) { port = remoteport; ipHostInfo = Dns.Resolve(remotehost); ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); obj_Socket.BeginConnect(remoteEP, new AsyncCallback( MyConnect), obj_Socket); remotehost = null; remoteport = 0; remoteEP = null; obj_Socket = null; } else { return; } } catch (SocketException) { SendLogMessage("IRC", "Connect", BlackLight.Services.Error.Errors.ERROR, "Problem with connect", "Unable to connect to specified host", "", ""); return; } catch (Exception ex) { SendLogMessage("IRC", "Connect", BlackLight.Services.Error.Errors.ERROR, "Problem with connect", "", ex.Message, ex.StackTrace); return; } }
private async Task DataUpdateStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var orderData = await _orderDataAccessor.GetAsync(stepContext.Context, () => new OrderData(), cancellationToken); CosmosClient client = new CosmosClient(Startup.CosmosDbEndpoint, Startup.AuthKey); database = await client.CreateDatabaseIfNotExistsAsync(databaseId); ContainerProperties containerProperties = new ContainerProperties(containerId, partitionKeyPath: Startup.PartitionKey); // Create with a throughput of 1000 RU/s container = await database.CreateContainerIfNotExistsAsync( containerProperties, throughput : 1000); //orderNum 가져오기 try { FeedIterator <DBdata> feedIterator = container.GetItemQueryIterator <DBdata>("SELECT top 1 * FROM c order by c._ts desc"); { while (feedIterator.HasMoreResults) { FeedResponse <DBdata> result = await feedIterator.ReadNextAsync(); foreach (var item in result) { orderData.OrderNum = Int32.Parse(item.id); } } } } catch (System.Exception e) { orderData.OrderNum = 0; } //ip IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); string ipAddr = string.Empty; for (int i = 0; i < host.AddressList.Length; i++) { if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { ipAddr = host.AddressList[i].ToString(); } } //Order 데이터 삽입 foreach (Sandwich tempSand in orderData.Sandwiches) { string sJson = JsonConvert.SerializeObject(tempSand); var dbData = new DBdata { id = $"{++orderData.OrderNum}", Contents = tempSand, ETag = "x", AccountNumber = ipAddr }; await container.CreateItemAsync <DBdata>(dbData, new PartitionKey(dbData.AccountNumber)); } //container 변경 containerProperties = new ContainerProperties(countContainerId, partitionKeyPath: "/AccountNumber"); // Create with a throughput of 1000 RU/s container = await database.CreateContainerIfNotExistsAsync( containerProperties, throughput : 1000); //Count 데이터 삽입 foreach (Sandwich tempSand in orderData.Sandwiches) { var CountId = 0; string sauce = ""; tempSand.Sauce.Sort(); foreach (string temp in tempSand.Sauce) { sauce += temp + " "; } //CountId 찾기 try { FeedIterator <DBcount> feedIterator = container.GetItemQueryIterator <DBcount>("SELECT top 1 * FROM c order by c._ts desc"); { while (feedIterator.HasMoreResults) { FeedResponse <DBcount> result = await feedIterator.ReadNextAsync(); foreach (var item in result) { CountId = Int32.Parse(item.id) + 1; } } } } catch (System.Exception e) { CountId = 0; } try { FeedIterator <DBcount> feedIterator = container.GetItemQueryIterator <DBcount>("SELECT * FROM c WHERE c.Sauce='" + sauce + "' and c.Bread ='" + tempSand.Bread + "' and c.Menu ='" + tempSand.Menu + "'"); { if (feedIterator.HasMoreResults) { FeedResponse <DBcount> result = await feedIterator.ReadNextAsync(); DBcount res = result.First(); var count = res.Count + 1; DBcount countData = new DBcount(); countData.id = res.id; countData.Count = count; countData.Sauce = sauce; countData.Menu = tempSand.Menu; countData.ETag = "x"; countData.AccountNumber = "0"; countData.Bread = tempSand.Bread; ItemResponse <DBcount> item = await container.DeleteItemAsync <DBcount>(partitionKey : new PartitionKey("0"), id : res.id); await container.CreateItemAsync(countData, new PartitionKey("0")); } } } catch (System.Exception e) { var countData = new DBcount { id = $"{CountId}", Count = 1, Bread = $"{tempSand.Bread}", Sauce = sauce, Menu = $"{tempSand.Menu}", ETag = "x", AccountNumber = "0" }; await container.CreateItemAsync <DBcount>(countData, new PartitionKey("0")); } } }
/// <summary> /// Populates the list with devices connected on LAN /// </summary> /// <param name="view">UI controls</param> /// <param name="InterfaceFriendlyName"></param> public static void StartScan(IView view, string InterfaceFriendlyName) { #region initialization if (capturedevice != null) { GatewayCalled = false; BackgroundScanDisabled = true; capturedevice.StopCapture(); capturedevice.Close(); capturedevice = null; } else { ClientList = new Dictionary <IPAddress, PhysicalAddress>(); Main.Devices = new ConcurrentDictionary <IPAddress, Device>(); } #endregion //Get list of interfaces CaptureDeviceList capturedevicelist = CaptureDeviceList.Instance; //crucial for reflection on any network changes capturedevicelist.Refresh(); capturedevice = (from devicex in capturedevicelist where ((NpcapDevice)devicex).Interface.FriendlyName == InterfaceFriendlyName select devicex).ToList()[0]; //open device in promiscuous mode with 1000ms timeout capturedevice.Open(DeviceMode.Promiscuous, 1000); //Arp filter capturedevice.Filter = "arp"; IPAddress myipaddress = AppConfiguration.LocalIp; //Probe for active devices on the network if (DiscoveryTimer == null) { StartDescoveryTimer(); } #region Retrieving ARP packets floating around and find out the sender's IP and MAC //Scan duration long scanduration = 8000; RawCapture rawcapture = null; //Main scanning task ScannerTask = Task.Run(() => { try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while ((rawcapture = capturedevice.GetNextPacket()) != null && stopwatch.ElapsedMilliseconds <= scanduration) { Packet packet = Packet.ParsePacket(rawcapture.LinkLayerType, rawcapture.Data); ArpPacket ArpPacket = packet.Extract <ArpPacket>(); if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize)) { ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress); string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress); string ip = ArpPacket.SenderProtocolAddress.ToString(); var device = new Device { IP = ArpPacket.SenderProtocolAddress, MAC = PhysicalAddress.Parse(mac.Replace(":", "")), DeviceName = "Resolving", ManName = "Getting information...", DeviceStatus = "Online" }; //Add device to UI list view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); })); //Add device to main device list _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device); //Get hostname and mac vendor for the current device _ = Task.Run(async() => { try { #region Get Hostname IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip); device.DeviceName = hostEntry?.HostName ?? ip; #endregion #region Get MacVendor var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; #endregion view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); })); } catch (Exception ex) { if (ex is SocketException) { var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; view.ListView1.BeginInvoke(new Action(() => { device.DeviceName = ip; view.ListView1.UpdateObject(device); })); } else { view.MainForm.BeginInvoke( new Action(() => { device.DeviceName = ip; device.ManName = "Error"; view.ListView1.UpdateObject(device); })); } } }); } int percentageprogress = (int)((float)stopwatch.ElapsedMilliseconds / scanduration * 100); view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning " + percentageprogress + "%")); } stopwatch.Stop(); view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = ClientList.Count.ToString() + " device(s) found")); //Initial scanning is over now we start the background scan. Main.OperationIsInProgress = false; //Start passive monitoring BackgroundScanStart(view); } catch { //Show an error in the UI in case something went wrong view.MainForm.Invoke(new Action(() => { view.StatusLabel.Text = "Error occurred"; view.PictureBox.Image = Properties.Resources.color_error; })); } }); #endregion }
public ResponseAPI Execute(HttpContext context, dynamic dataReq = null) { ResponseAPI res = new ResponseAPI(); StringValues HToken; context.Request.Headers.TryGetValue("Token", out HToken); Token = HToken.ToString(); DateTime StartTime = DateTime.Now; string StackTraceMsg = string.Empty; try { StringValues HAccessToken; context.Request.Headers.TryGetValue("AccessToken", out HAccessToken); AccessToken = HAccessToken.ToString(); IPHostEntry heserver = Dns.GetHostEntry(Dns.GetHostName()); IPAddress = /*string.Join(',', heserver.AddressList.Select(x => x.ToString()).ToList());*/ context.Connection.RemoteIpAddress.ToString(); StringValues HUserAgent; context.Request.Headers.TryGetValue("User-Agent", out HUserAgent); UserAgent = HUserAgent.ToString(); StringValues HRecaptchaResponse; context.Request.Headers.TryGetValue("RecaptchaResponse", out HRecaptchaResponse); RecaptchaResponse = HRecaptchaResponse.ToString(); // if (!this.GetType().Name.Equals("OauthAccessTokenGet")) this.ValidatePermission(); /* * StringValues Husercode; * context.Request.Headers.TryGetValue("UserCode", out Husercode); * UserCode = Husercode.ToString(); */ if (dataReq != null) { try { dataReq = this.MappingRequest(dataReq); } catch (Exception) { dataReq = this.MappingRequestArr(dataReq); } } this.ExecuteChild(dataReq, res); res.code = "S0001"; res.message = "SUCCESS"; res.status = "S"; } catch (Exception ex) { StackTraceMsg = ex.StackTrace; //map error code, message ErrorCode error = EnumUtil.GetEnum <ErrorCode>(ex.Message); res.code = error.ToString(); if (res.code == ErrorCode.U000.ToString()) { res.message = ex.Message; } else { res.message = error.GetDescription(); } res.status = "F"; } finally { ASSETKKF_ADO.Mssql.Mcis.muAPILogAdo.GetInstant().Insert(new ASSETKKF_MODEL.Data.Mssql.Mcis.muAPILog() { Token = Token, APIName = this.GetType().Name, //RefID = this.Logger.RefID, ServerName = Environment.MachineName, StartDate = StartTime, EndDate = DateTime.Now, Status = res.status, StatusMessage = res.message, Input = this.GetType().Name.Equals("OauthLogin") ? "" : JsonConvert.SerializeObject(dataReq), Output = JsonConvert.SerializeObject(res), Remark = StackTraceMsg }); } return(res); }
private static void UrlVerify() { string url = null; do { ForegroundColor = ConsoleColor.Cyan; WriteLine("Informe um endereço válido de internet."); url = Console.ReadLine(); }while (string.IsNullOrWhiteSpace(url)); var uri = new Uri(url); WriteLine(""); WriteHiglightMessage($"Url: {uri}\n"); WriteHiglightMessage($"Scheme: {uri.Scheme}\n"); WriteHiglightMessage($"Port: {uri.Port}\n"); WriteHiglightMessage($"Host: {uri.Host}\n"); WriteHiglightMessage($"Path: {uri.AbsolutePath}\n"); WriteHiglightMessage($"Query: {uri.Query}\n"); WriteLine(""); IPHostEntry entry = Dns.GetHostEntry(uri.Host); WriteLine($"{entry.HostName} possui os seguintes endereços de IP:"); WriteLine(""); foreach (IPAddress address in entry.AddressList) { WriteLine($" {address}"); } WriteLine(""); var ping = new Ping(); WriteLine("Realizando o ping para o servidor, por favor, aguarde..."); WriteLine(""); PingReply reply = ping.Send(uri.Host); Write("O servidor foi pingado e retornou o seguinte status: "); if (reply.Status == IPStatus.Success) { ForegroundColor = ConsoleColor.Green; } else { ForegroundColor = ConsoleColor.Red; } Write(reply.Status); WriteLine(""); ForegroundColor = ConsoleColor.Cyan; if (reply.Status == IPStatus.Success) { WriteLine($"O tempo de resposta foi de: {reply.RoundtripTime:N0}ms para {reply.Address}\n"); } WriteHiglightMessage("\nPressione uma tecla para finalizar.\n"); }
private bool ConnectProcess(CONNECT_TYPE ConnectType) { IPAddress host; if (IPAddress.TryParse(ServerHost, out host) == false) { IPHostEntry ipHostInfo = Dns.GetHostEntry(ServerHost); host = ipHostInfo.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).First(); } else { host = IPAddress.Parse(ServerHost); } ServerEndPoint = new IPEndPoint(host, PortNumber); clientInfo.ConnectDate = DateTime.Now; try { //TCP接続 serverSocket = new TcpClient(ServerEndPoint.Address.ToString(), ServerEndPoint.Port); var serverSetting = ReceiveServerSetting(serverSocket.GetStream()); Stream CommunicateStream; if (serverSetting.UseSSL == true) { SslStream sslStream = new SslStream(serverSocket.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(ServerHost); CommunicateStream = sslStream as Stream; } else { CommunicateStream = serverSocket.GetStream(); } Logger.LogInformation("Socket connected to {0}", serverSocket.ToString()); //接続出来たらクライアント情報を送る SendClientInfo(CommunicateStream, clientInfo); //Udp接続 var UdpInfo = ConnectUdp(ServerHost, ReceiveUdpPort(CommunicateStream)); //受信スレッド作成 clientReceiver.Run(handler: serverSocket, _stream: CommunicateStream, UdpSocket: UdpInfo.socket, UdpEndPort: UdpInfo.point, clientInfo: clientInfo, _logger: Logger, Parent); } catch (ArgumentNullException ane) { Logger.LogError("ArgumentNullException : {0}", ane.ToString()); throw ane; } catch (IOException ex) { if (ex.HResult == -2146232800) { Logger.LogError("IOException : {0}", ex.ToString()); throw ex; } return(false); } catch (SocketException ex) { //Logger.LogError("SocketException : {0}", ex.ToString()); return(false); } catch (Exception e) { Logger.LogError("Unexpected exception : {0}", e.ToString()); //throw e; } return(true); }
internal static RubyArray /*!*/ CreateHostEntryArray(RubyContext /*!*/ context, IPHostEntry /*!*/ hostEntry, bool packIpAddresses) { RubyArray result = new RubyArray(4); // host name: result.Add(HostNameToMutableString(context, hostEntry.HostName)); // aliases: RubyArray aliases = new RubyArray(hostEntry.Aliases.Length); foreach (string alias in hostEntry.Aliases) { aliases.Add(HostNameToMutableString(context, alias)); } result.Add(aliases); // address (the first IPv4): foreach (IPAddress address in hostEntry.AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { result.Add((int)address.AddressFamily); if (packIpAddresses) { byte[] bytes = address.GetAddressBytes(); MutableString str = MutableString.CreateBinary(); str.Append(bytes, 0, bytes.Length); result.Add(str); } else { result.Add(MutableString.CreateAscii(address.ToString())); } break; } } return(result); }
private void ProcessSocket(Socket requestSocket) { using (requestSocket) { if (requestSocket.Connected) { bool IsHttps = false; GetMessageFromSocket(requestSocket, out byte[] httpByteArray); string[] httpFields = SplitHttpToArray(httpByteArray); string hostField = httpFields.FirstOrDefault(x => x.Contains("Host")); if (hostField == null) { return; } int UsedPort = 0; string[] hostFields = hostField.Split(' '); string host = hostFields[1]; bool isClosed = IsBlocked(host); try { if (host.IndexOf(':') != -1) { string[] trueports = host.Split(':'); portInt = int.Parse(trueports[1]); IsHttps = true; } if (isClosed) { SendErrorPage(requestSocket, host); Console.WriteLine(" {0} in black list.", host); return; } else { if (IsHttps) { UsedPort = portInt; } else { UsedPort = sendPort; } Console.WriteLine("request to " + hostField + "|| port: " + UsedPort); IPHostEntry ipHostEntry = Dns.GetHostEntry(host); IPEndPoint ipEndPoint = new IPEndPoint(ipHostEntry.AddressList[0], UsedPort); using (Socket replySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { replySocket.Connect(ipEndPoint); if (replySocket.Send(httpByteArray, httpByteArray.Length, SocketFlags.None) != httpByteArray.Length) { Console.WriteLine("Can''t connect "); } else { GetMessageFromSocket(replySocket, out byte[] httpResponse); requestSocket.Send(httpResponse, httpResponse.Length, SocketFlags.None); httpFields = SplitHttpToArray(httpResponse); string[] responseCode = httpFields[0].Split(' '); if (responseCode == null) { return; } Console.WriteLine("{0} answer code: {1}", hostField, responseCode[1]); } } } requestSocket.Close(); } catch (Exception) { Console.WriteLine("Данный порт не поддерживается(порт: {0})", portInt); } } } }
/// <summary> /// 启动 /// </summary> private void Run() { if (isDisposed == true) { throw new ObjectDisposedException("ZYServer is Disposed"); } IPEndPoint myEnd = new IPEndPoint(IPAddress.Any, Port); if (!Host.Equals("any", StringComparison.CurrentCultureIgnoreCase)) { if (String.IsNullOrEmpty(Host)) { IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress s in p.AddressList) { if (!s.IsIPv6LinkLocal && s.AddressFamily != AddressFamily.InterNetworkV6) { myEnd = new IPEndPoint(s, Port); break; } } } else { try { myEnd = new IPEndPoint(IPAddress.Parse(Host), Port); } catch (FormatException) { IPHostEntry p = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress s in p.AddressList) { if (!s.IsIPv6LinkLocal) { myEnd = new IPEndPoint(s, Port); } } } } } sock = new Socket(myEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); if (Environment.OSVersion.Platform.ToString().IndexOf("NT", StringComparison.Ordinal) >= 0) //WINDOWS NT平台 { uint dummy = 0; byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0); BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy)); BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2); sock.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); } sock.Bind(myEnd); sock.Listen(20); SendTimeout = 1000; ReceiveTimeout = 1000; BuffManagers = new BufferManager(MaxConnectCout * MaxBufferSize, MaxBufferSize); BuffManagers.Inint(); SocketAsynPool = new SocketAsyncEventArgsPool(MaxConnectCout); for (int i = 0; i < MaxConnectCout; i++) { SocketAsyncEventArgs socketasyn = new SocketAsyncEventArgs(); socketasyn.Completed += new EventHandler <SocketAsyncEventArgs>(Asyn_Completed); SocketAsynPool.Push(socketasyn); } Accept(); }
// TODO: Might be moved and refactored when is needed for other tasks public static string GetBaseAddress(string networkHost, int?httpPort) { var port = httpPort ?? DefaultHttpPort; if (string.IsNullOrEmpty(networkHost)) { return($"http://localhost:{port}/"); } var host = networkHost; if (networkHost.IndexOf(',') >= 0) // Uri host must not contain comma, but elasticsearch.yml supports it { var hosts = networkHost.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(h => h.Trim()); host = hosts.FirstOrDefault(h => h == "localhost" || h == "127.0.0.1" || h == LocalhostPlaceholder || h == LocalhostV4Placeholder || h == LocalhostV6Placeholder) // prefer local interface ?? hosts.First(); } switch (host) { case LocalhostPlaceholder: host = "localhost"; break; case LocalhostV4Placeholder: host = "127.0.0.1"; break; case LocalhostV6Placeholder: host = "[::1]"; break; //TODO: differentiate between _site_ and _global_ case SiteAddressPlaceholder: case GlobalAddressPlaceholder: case SiteAddressV4Placeholder: case GlobalAddressV4Placeholder: case SiteAddressV6Placeholder: case GlobalAddressV6Placeholder: IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName()); var ipAddresses = ipHostEntry.AddressList .Where(a => !IPAddress.IsLoopback(a) && (a.AddressFamily == AddressFamily.InterNetwork || a.AddressFamily == AddressFamily.InterNetworkV6)); if (host == SiteAddressV4Placeholder || host == GlobalAddressV4Placeholder) { ipAddresses = ipAddresses.Where(a => a.AddressFamily == AddressFamily.InterNetwork); } if (host == SiteAddressV6Placeholder || host == GlobalAddressV6Placeholder) { ipAddresses = ipAddresses.Where(a => a.AddressFamily == AddressFamily.InterNetworkV6); } var ipAddress = ipAddresses.First(); host = ipAddress.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{ipAddress}]" : ipAddress.ToString(); break; } // do not remove trailing slash. Base address *must* have it var baseAddress = $"http://{host}:{port}/"; if (!Uri.IsWellFormedUriString(baseAddress, UriKind.Absolute)) { // uri is not right, as installation is always local it's better to try localhost anyway baseAddress = $"http://localhost:{port}/"; } return(baseAddress); }
/// <summary> /// Gets the terminal IP. /// </summary> /// <returns></returns> public static string GetTerminalIP() { IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); return(ipHostInfo.AddressList[0].ToString()); }
public static void StartListening(string host, int port) { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; // Establish the local endpoint for the socket. // Dns.GetHostName returns the name of the // host running the application. IPHostEntry ipHostInfo = Dns.GetHostEntry(host); IPAddress ipAddress = ipHostInfo.AddressList[1]; Console.WriteLine($"Server IP:{ipAddress}"); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and // listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(10); // Start listening for connections. while (true) { Console.WriteLine("Waiting for a connection..."); // Program is suspended while waiting for an incoming connection. Socket handler = listener.Accept(); data = null; // An incoming connection needs to be processed. while (true) { int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesRec); // Show the data on the console. Console.WriteLine("Text received : {0}", data); // Echo the data back to the client. byte[] replay = Encoding.ASCII.GetBytes(data); handler.Send(replay); if (data.IndexOf("<EOF>") > -1) { break; } } // Show the data on the console. Console.WriteLine("Text received : {0}", data); // Echo the data back to the client. byte[] msg = Encoding.ASCII.GetBytes(data); handler.Send(msg); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); }
public string MakeInnerHtmlChart(ChartData[] cds, int Width, int Height) { //Check that we have some data if (cds == null) { return("An error occured, could not find any plots!"); } try { //Get paths, set in global.cs string RelativePath = (string)Application["RelativePath"] + "/"; string AbsolutePath = (string)Application["PhysicalPath"] + "/"; //Generate unique filename string filename = DateTime.Now.Ticks.ToString(); //Get hostinfo IPHostEntry ihe = Dns.GetHostByName(this.Server.MachineName); //Initialize variables string[] imgs = new string[cds.Length]; StringBuilder sr = new StringBuilder(); string[] datanames = new string[cds.Length]; string xmldata; string tabdata; ArrayList files = new ArrayList(); //Run through ChartData[] and create charts for (int i = 0; i < cds.Length; i++) { //Initialize chart ChartControl cc = new ChartControl(); cc.AddChartData(cds[i]); cc.BackColor = Color.White; //Check X and Y values if (cds[i].X == null || cds[i].Y == null) { continue; } //Check y values bool ok = false; foreach (double[] d in cds[i].Y) { if (d != null) { ok = true; } } if (!ok) { continue; } //Check if the current ChartData has Width and Height set try { if (cds[i].Width != 0) { cc.Width = cds[i].Width; } else { cc.Width = Width; } if (cds[i].Height != 0) { cc.Height = cds[i].Height; } else { cc.Height = Height; } } catch {} //Create Image Image img = cc.GetImage(); if (img == null) { continue; } //Save image to disk img.Save(AbsolutePath + filename + "_" + i + ".png", ImageFormat.Png); //Store relative path to image imgs[i] = RelativePath + filename + "_" + i + ".png"; //Save ChartData as XML try { xmldata = filename + "_" + i + ".xnc"; using (Stream s = File.OpenWrite(AbsolutePath + xmldata)) { cds[i].ToXML(s); } } catch { xmldata = null; } //Save ChartData as HTML try { tabdata = filename + "_" + i + ".html"; using (Stream s = File.OpenWrite(AbsolutePath + tabdata)) { cds[i].ToHtml(s); } } catch { tabdata = null; } //Create HTML to return to client sr.Append("<table cellpadding=0 cellspacing=2><tr><td >"); sr.Append("<img src='" + "http://" + ihe.HostName + imgs[i] + "'>\n"); if (xmldata != null) { sr.Append("<tr><td align=right><a href='http://" + ihe.HostName + RelativePath + xmldata + "'>Xml format</a> | "); } if (tabdata != null) { sr.Append("<a href='http://" + ihe.HostName + RelativePath + tabdata + "' target='htmldata'>Html format</a></table><br>"); } //Files to be deleted at the end of session files.Add(AbsolutePath + filename + "_" + i + ".png"); files.Add(AbsolutePath + xmldata); files.Add(AbsolutePath + tabdata); } //Add to session end delete AddToDelete((string[])files.ToArray(typeof(string))); //Return HTML return(sr.ToString()); } catch (Exception e) { return("An unknown error occured. Please send the following message to the administrator:<br>" + e.Message + "<br>" + e.StackTrace + "<br>" + cds.Length + ", " + Width + ", " + Height); } }
public List <IPAddress> getPossibleIpAddresses() { IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); return(ipHost.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToList()); }
private IPHostEntry MakeEntry(string hostName) { var response = Query(hostName, QType.A, QClass.IN); var addresses = new List<IPAddress>(); var aliases = new List<string>(); foreach (var answerRR in response.Answers) { if (answerRR.Type == RecordType.A) { // answerRR.RECORD.ToString() == (answerRR.RECORD as RecordA).Address addresses.Add(IPAddress.Parse((answerRR.RECORD.ToString()))); hostName = answerRR.NAME; } else { if (answerRR.Type == RecordType.CNAME) { aliases.Add(answerRR.NAME); } } } var result = new IPHostEntry(hostName, addresses.ToArray(), aliases.ToArray()); return result; }
public dnsLookupDocument(IPHostEntry __hostEntry, String domainName) { deploy(__hostEntry, domainName); }
static void Main(string[] args) { String dc_address = ""; if (args == null || args.Length <= 0) { Console.WriteLine("usage: SharpAdidnsdumpis.exe dc-address"); return; } else { dc_address = args[0]; } try { Console.WriteLine("Running enumeration against {0}", dc_address); String rootDn = "DC=DomainDnsZones"; String domain_local = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; String domain_path = ""; foreach (String domain_path_r in domain_local.Split('.')) { domain_path += ",DC=" + domain_path_r; } rootDn += domain_path; Console.WriteLine("Running enumeration against {0}", "LDAP://" + dc_address + "/" + rootDn); DirectoryEntry rootEntry = new DirectoryEntry("LDAP://" + dc_address + "/" + rootDn); rootEntry.AuthenticationType = AuthenticationTypes.Delegation; DirectorySearcher searcher = new DirectorySearcher(rootEntry); //find domains var queryFormat = "(&(objectClass=DnsZone)(!(DC=*arpa))(!(DC=RootDNSServers)))"; searcher.Filter = queryFormat; searcher.SearchScope = SearchScope.Subtree; foreach (SearchResult result in searcher.FindAll()) { String domain = (result.Properties["DC"].Count > 0 ? result.Properties["DC"][0].ToString() : string.Empty); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Domain: {0}", domain); Console.WriteLine(); DirectoryEntry rootEntry_d = new DirectoryEntry("LDAP://" + dc_address + "/DC=" + result.Properties["DC"][0].ToString() + ",CN=microsoftdns," + rootDn); rootEntry_d.AuthenticationType = AuthenticationTypes.Delegation; DirectorySearcher searcher_h = new DirectorySearcher(rootEntry_d); //find hosts queryFormat = "(&(!(objectClass=DnsZone))(!(DC=@))(!(DC=*arpa))(!(DC=*DNSZones)))"; searcher_h.Filter = queryFormat; searcher_h.SearchScope = SearchScope.Subtree; foreach (SearchResult result_h in searcher_h.FindAll()) { String target = ""; if (result_h.Properties["DC"].Count > 0) { target = result_h.Properties["DC"][0].ToString(); } else { //Hidden entry String path = result_h.Path; target = (path.Substring(path.IndexOf("LDAP://" + dc_address + "/"), path.IndexOf(","))).Split('=')[1]; } if (!target.EndsWith(".")) { target += "." + domain; } Boolean tombstoned = result_h.Properties["dNSTombstoned"].Count > 0 ? (Boolean)result_h.Properties["dNSTombstoned"][0] : false; try { IPHostEntry hostInfo = Dns.GetHostEntry(target); foreach (IPAddress result_ip in hostInfo.AddressList) { Console.WriteLine("Host {0} {1}", target, result_ip); } } catch (Exception e) { if (tombstoned) { Console.WriteLine("Host {0} Tombstoned", target); } else { Console.WriteLine("DNS Query with target : {0} failed", target); } } } } Console.WriteLine(); Console.WriteLine("SharpAdidnsdump end"); Console.WriteLine(); return; } catch (Exception e) { Console.WriteLine("Error retriving data : {0}", e.Message); return; } }
/// <summary> /// Actively monitor ARP packets for signs of new clients after the scanner is done. This method should be called from the StartScan method. /// </summary> /// <param name="view">UI controls</param> public static void BackgroundScanStart(IView view) { view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Starting background scan...")); BackgroundScanDisabled = false; IPAddress myipaddress = AppConfiguration.LocalIp; #region Assign OnPacketArrival event handler and start capturing capturedevice.OnPacketArrival += (object sender, CaptureEventArgs e) => { if (BackgroundScanDisabled) { return; } Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); if (packet == null) { return; } ArpPacket ArpPacket = packet.Extract <ArpPacket>(); if (!ClientList.ContainsKey(ArpPacket.SenderProtocolAddress) && ArpPacket.SenderProtocolAddress.ToString() != "0.0.0.0" && Tools.AreCompatibleIPs(ArpPacket.SenderProtocolAddress, myipaddress, AppConfiguration.NetworkSize)) { ClientList.Add(ArpPacket.SenderProtocolAddress, ArpPacket.SenderHardwareAddress); view.ListView1.Invoke(new Action(() => { string mac = Tools.GetMACString(ArpPacket.SenderHardwareAddress); string ip = ArpPacket.SenderProtocolAddress.ToString(); var device = new Device { IP = ArpPacket.SenderProtocolAddress, MAC = PhysicalAddress.Parse(mac.Replace(":", "")), DeviceName = "Resolving", ManName = "Getting information...", DeviceStatus = "Online" }; //Add device to list view.ListView1.BeginInvoke(new Action(() => { view.ListView1.AddObject(device); })); //Add device to main device list _ = Main.Devices.TryAdd(ArpPacket.SenderProtocolAddress, device); //Get hostname and mac vendor for the current device _ = Task.Run(async() => { try { #region Get Hostname IPHostEntry hostEntry = await Dns.GetHostEntryAsync(ip); device.DeviceName = hostEntry?.HostName ?? ip; #endregion #region Get MacVendor var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; #endregion view.ListView1.BeginInvoke(new Action(() => { view.ListView1.UpdateObject(device); })); } catch (Exception ex) { if (ex is SocketException) { var Name = VendorAPI.GetVendorInfo(mac); device.ManName = (Name is null) ? "" : Name.data.organization_name; view.ListView1.BeginInvoke(new Action(() => { device.DeviceName = ip; view.ListView1.UpdateObject(device); })); } else { view.MainForm.BeginInvoke( new Action(() => { device.DeviceName = ip; device.ManName = "Error"; view.ListView1.UpdateObject(device); })); } } }); })); view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found")); } else if (ClientList.ContainsKey(ArpPacket.SenderProtocolAddress)) { foreach (var Device in Main.Devices) { if (Device.Key.Equals(ArpPacket.SenderProtocolAddress)) { Device.Value.TimeSinceLastArp = DateTime.Now; break; } } } }; //Start receiving packets capturedevice.StartCapture(); //Update UI state view.MainForm.BeginInvoke(new Action(() => { view.PictureBox.Image = NetStalker.Properties.Resources.color_ok; view.StatusLabel2.Text = "Ready"; view.Tile.Enabled = true; view.Tile2.Enabled = true; })); if (!LoadingBarCalled) { CallTheLoadingBar(view); view.MainForm.BeginInvoke(new Action(() => view.StatusLabel.Text = "Scanning...")); } view.MainForm.Invoke(new Action(() => view.StatusLabel.Text = ClientList.Count + " device(s) found")); #endregion }
public TCPListener(Protocol protocol) : base(protocol) { ipHostInfo = Dns.Resolve(Dns.GetHostName()); ipAddress = ipHostInfo.AddressList[0]; localEndPoint = new IPEndPoint(ipAddress, 11000); listener = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listener.Bind(localEndPoint); }
/// <summary> /// Overrides the ConvertFrom method of IConvertFrom. /// </summary> /// <param name="source">the object to convert to an IPAddress</param> /// <returns>the IPAddress</returns> /// <remarks> /// <para> /// Uses the <see cref="IPAddress.Parse"/> method to convert the /// <see cref="String"/> argument to an <see cref="IPAddress"/>. /// If that fails then the string is resolved as a DNS hostname. /// </para> /// </remarks> /// <exception cref="ConversionNotSupportedException"> /// The <paramref name="source"/> object cannot be converted to the /// target type. To check for this condition use the <see cref="CanConvertFrom"/> /// method. /// </exception> public object ConvertFrom(object source) { string str = source as string; if (str != null && str.Length > 0) { try { #if NET_2_0 || NETCF_2_0 #if !NETCF_2_0 // Try an explicit parse of string representation of an IPAddress (v4 or v6) IPAddress result; if (IPAddress.TryParse(str, out result)) { return(result); } #endif // Try to resolve via DNS. This is a blocking call. // GetHostEntry works with either an IPAddress string or a host name IPHostEntry host = Dns.GetHostEntry(str); if (host != null && host.AddressList != null && host.AddressList.Length > 0 && host.AddressList[0] != null) { return(host.AddressList[0]); } #else // Before .NET 2 we need to try to parse the IPAddress from the string first // Check if the string only contains IP address valid chars if (str.Trim(validIpAddressChars).Length == 0) { try { // try to parse the string as an IP address return(IPAddress.Parse(str)); } catch (FormatException) { // Ignore a FormatException, try to resolve via DNS } } // Try to resolve via DNS. This is a blocking call. #if NETSTANDARD2_0 IPHostEntry host = Dns.GetHostEntryAsync(str).GetAwaiter().GetResult(); #else IPHostEntry host = Dns.GetHostByName(str); #endif if (host != null && host.AddressList != null && host.AddressList.Length > 0 && host.AddressList[0] != null) { return(host.AddressList[0]); } #endif } catch (Exception ex) { throw ConversionNotSupportedException.Create(typeof(IPAddress), source, ex); } } throw ConversionNotSupportedException.Create(typeof(IPAddress), source); }