public class GlobalFunction { public static void writeLOG(string loggg) { // string path = @"bin\logfile.log"; string time = DateTime.Now.ToString("hh:mm:ss"); string date = DateTime.Now.ToString("yyyy.MM.dd"); string logging = date + " " + time + " " + loggg; using (StreamWriter sw = File.AppendText(path)) { sw.WriteLine(logging); } } public static void writeLOGdebug(string loggg) { try { // string path = @"bin\logfile.log"; string time = DateTime.Now.ToString("hh:mm:ss"); string date = DateTime.Now.ToString("yyyy.MM.dd"); string logging = date + " " + time + " " + loggg; using (StreamWriter sw = File.AppendText(path)) { sw.WriteLine(logging); } } catch (Exception exc) { } } } public class Globals { public static IPAddress localip = "192.168.88.23"; public static int _localServerPort = 19991; public const int _maxMessage = 100; public static string _LocalUserName = "375297770001"; public struct MessBuffer { public string usernameLocal; public string usernamePeer; public string message; } public static List<MessBuffer> MessagesBase = new List<MessBuffer>(); public static List<MessBuffer> MessagesBaseSelected = new List<MessBuffer>(); } public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } public partial class ViewController : UIViewController { public static ManualResetEvent allDone = new ManualResetEvent(false); public void startLocalServer() { //IPHostEntry ipHost = Dns.GetHostEntry(_serverHost); //IPAddress ipAddress = ipHost.AddressList[0]; IPAddress ipAddress = Globals.localip; IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Globals._localServerPort); Socket socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Bind(ipEndPoint); socket.Listen(1000); GlobalFunction.writeLOGdebug("Local Server has been started on IP: " + ipEndPoint); while (true) { try { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. socket.BeginAccept( new AsyncCallback(AcceptCallback), socket); // Wait until a connection is made before continuing. allDone.WaitOne(); } catch (Exception exp) { GlobalFunction.writeLOGdebug("Error. Failed startLocalServer() method: " + Convert.ToString(exp)); } } } public void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } public void ReadCallback(IAsyncResult ar) { String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.UTF8.GetString( state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString(); if (content.IndexOf("<EOF>") > -1) { // All the data has been read from the // client. Display it on the console. string[] bfd = content.Split(new char[] { '|' }, StringSplitOptions.None); string decrypt = MasterEncryption.MasterDecrypt(bfd[0]); string[] bab = decrypt.Split(new char[] { '~' }, StringSplitOptions.None); Globals.MessBuffer Bf = new Globals.MessBuffer(); Bf.message = bab[2]; Bf.usernamePeer = bab[0]; Bf.usernameLocal = bab[1]; string upchat_m = "[" + bab[1] + "]# " + bab[2]; this.InvokeOnMainThread(delegate { frm.messageField1.InsertText(Environment.NewLine + "[" + bab[1] + "]# " + bab[2]); }); //if (Ok != null) { Ok(this, upchat_m); } Globals.MessagesBase.Add(Bf); //GlobalFunction.writeLOGdebug("Received message: " + content); // Echo the data back to the client. //Send(handler, content); } else { handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } } } }
public static class Program { private static Thread _serverLocalThread; /// <summary> /// The main entry point for the application. /// </summary> /// [STAThread] static void Main() { _serverLocalThread = new Thread(GlobalFunction.startLocalServer); _serverLocalThread.IsBackground = true; _serverLocalThread.Start(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }
public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } private void connectToRemotePeer(IPAddress ipAddress) { try { IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Globals._localServerPort); _serverSocketClientRemote = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _serverSocketClientRemote.Connect(ipEndPoint); GlobalFunction.writeLOGdebug("We connected to: " + ipEndPoint); } catch (Exception exc) { GlobalFunction.writeLOGdebug("Error. Failed connectToRemotePeer(string iphost) method: " + Convert.ToString(exc)); } } private void sendDataToPeer(string textMessage) { try { byte[] buffer = Encoding.UTF8.GetBytes(textMessage); int bytesSent = _serverSocketClientRemote.Send(buffer); GlobalFunction.writeLOGdebug("Sended data: " + textMessage); } catch (Exception exc) { GlobalFunction.writeLOGdebug("Error. Failed sendDataToPeer(string testMessage) method: " + Convert.ToString(exc)); } } private void Client_listner() { try { while (_serverSocketClientRemote.Connected) { byte[] buffer = new byte[8196]; int bytesRec = _serverSocketClientRemote.Receive(buffer); string data = Encoding.UTF8.GetString(buffer, 0, bytesRec); //string data1 = encryption.Decrypt(data); if (data.Contains("#updatechat")) { //UpdateChat(data); GlobalFunction.writeLOGdebug("Chat updated with: " + data); continue; } } } catch (Exception exc) { GlobalFunction.writeLOGdebug("Error. Failed Client_listner() method: " + Convert.ToString(exc)); } } private void sendMessage() { try { connectToRemotePeer(Globals._peerRemoteServer); _RemoteclientThread = new Thread(Client_listner); _RemoteclientThread.IsBackground = true; _RemoteclientThread.Start(); string data = inputTextBox.Text; Globals.MessBuffer ba = new Globals.MessBuffer(); ba.usernameLocal = Globals._LocalUserName; ba.usernamePeer = Globals._peerRemoteUsername; ba.message = data; Globals.MessagesBase.Add(ba); if (string.IsNullOrEmpty(data)) return; string datatopeer = Globals._peerRemoteUsername + "~" + Globals._LocalUserName + "~" + data; string datatopeerEncrypted = MasterEncryption.MasterEncrypt(datatopeer); sendDataToPeer(datatopeerEncrypted + "|<EOF>"); addLineToChat(data, Globals._LocalUserName); inputTextBox.Text = string.Empty; } catch (Exception exp) { GlobalFunction.writeLOGdebug(Convert.ToString(exp)); } } private void addLineToChat(string msg, string username) { messageField1.InsertText(Environment.NewLine + "[" + username + "]# " + msg); } public void addFromServer(string msg, string username) { messageField1.InsertText(Environment.NewLine + "[" + username + "]# " + msg); } private void listBox1_Click() { messageField1.Text = ""; Globals.MessagesBaseSelected.Clear(); GlobalFunction.ReloadLocalBufferForSelected(); for (int i = 0; i < Globals.MessagesBaseSelected.Count; i++) { messageField1.InsertText(Environment.NewLine + "[" + Globals.MessagesBaseSelected[i].usernameLocal + "]# " + Globals.MessagesBaseSelected[i].message); } Globals._peerRemoteServer = GlobalFunction.getPEERIPbySOAPRequest(Globals._peerRemoteUsername); string Name = Globals._LocalUserName; GlobalFunction.writeLOGdebug("Local name parameter listBox1_DoubleClick: " + Name); connectToRemotePeer(Globals._peerRemoteServer); _RemoteclientThread = new Thread(Client_listner); _RemoteclientThread.IsBackground = true; _RemoteclientThread.Start(); } public static ViewController Form;
iptables -A INPUT -i ens160 -p tcp -m tcp --dport 8443 -j ACCEPT iptables -A INPUT -i ens160 -p udp -m udp --dport 8443 -j ACCEPT iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT iptables -A INPUT -i ens192 -j ACCEPT iptables -P INPUT DROP iptables -t nat -A PREROUTING -p tcp -m tcp -d 10.0.141.1 --dport 443 -j DNAT --to-destination 10.24.184.179:443 #iptables -t nat -A PREROUTING -p udp -m udp -d 10.0.141.1 --dport 53 -j DNAT --to-destination 10.24.214.124:53
def updatezone(username,ipaddress) p data = {"rrsets": [ {"name": "#{username}.spectrum.loc.", "type": "A", "ttl": 86400, "changetype": "REPLACE", "records": [ {"content": ipaddress, "disabled": false } ] } ] } url = 'http://10.24.214.124:7777/api/v1/servers/localhost/zones/spectrum.loc.' uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Patch.new(uri.request_uri) req["X-API-Key"]="1234567890" req.body = data.to_json p "fd" p response = http.request(req) p content = response.body end
public static void registerSession2() { try { CallWebServiceUpdateLocation(); writeLOG("Session registered on SoapGW."); } catch (Exception exc) { writeLOG("Error. Failed GlobalFunction.registerSession2() method: " + Convert.ToString(exc)); } } private static HttpWebRequest CreateWebRequest(string url, string action) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Headers.Add("SOAPAction", action); webRequest.ContentType = "text/xml;charset=\"utf-8\""; webRequest.Accept = "text/xml"; webRequest.Method = "POST"; return webRequest; } private static XmlDocument CreateSoapEnvelope() { XmlDocument soapEnvelopeDocument = new XmlDocument(); string xml = System.String.Format(@" <soapenv:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:spec=""https://spectrum.master""> <soapenv:Header/> <soapenv:Body> <master_update_location soapenv:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""> <ipaddress xsi:type=""xsd:string"">{0}</ipaddress> <username xsi:type=""xsd:string"">{1}</username> </master_update_location> </soapenv:Body> </soapenv:Envelope> ", Convert.ToString(Globals.localip), Globals._LocalUserName); soapEnvelopeDocument.LoadXml(xml); return soapEnvelopeDocument; } public static void CallWebServiceUpdateLocation() { var _url = "http://10.0.141.1/master/action"; var _action = "master_update_location"; XmlDocument soapEnvelopeXml = CreateSoapEnvelope(); HttpWebRequest webRequest = CreateWebRequest(_url, _action); InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest); // begin async call to web request. IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); // suspend this thread until call is complete. You might want to // do something usefull here like update your UI. asyncResult.AsyncWaitHandle.WaitOne(); // get the response from the completed web request. string soapResult; using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) { using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); } //Console.Write(soapResult); } } private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) { using (Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } }
Source: https://habr.com/ru/post/346792/
All Articles