Search Results

Search found 291 results on 12 pages for 'ipaddress'.

Page 11/12 | < Previous Page | 7 8 9 10 11 12  | Next Page >

  • SQL putting two single quotes around datetime fields and fails to insert record

    - by user82613
    I am trying to INSERT into an SQL database table, but it doesn't work. So I used the SQL server profiler to see how it was building the query; what it shows is the following: declare @p1 int set @p1=0 declare @p2 int set @p2=0 declare @p3 int set @p3=1 exec InsertProcedureName @ConsumerMovingDetailID=@p1 output, @UniqueID=@p2 output, @ServiceID=@p3 output, @ProjectID=N'0', @IPAddress=N'66.229.112.168', @FirstName=N'Mike', @LastName=N'P', @Email=N'[email protected]', @PhoneNumber=N'(254)637-1256', @MobilePhone=NULL, @CurrentAddress=N'', @FromZip=N'10005', @MoveInAddress=N'', @ToZip=N'33067', @MovingSize=N'1', @MovingDate=''2009-04-30 00:00:00:000'', /* Problem here ^^^ */ @IsMovingVehicle=0, @IsPackingRequired=0, @IncludeInSaveologyPlanner=1 select @p1, @p2, @p3 As you can see, it puts a double quote two pairs of single quotes around the datetime fields, so that it produces a syntax error in SQL. I wonder if there is anything I must configure somewhere? Any help would be appreciated. Here is the environment details: Visual Studio 2008 .NET 3.5 MS SQL Server 2005 Here is the .NET code I'm using.... //call procedure for results strStoredProcedureName = "usp_SMMoverSearchResult_SELECT"; Database database = DatabaseFactory.CreateDatabase(); DbCommand dbCommand = database.GetStoredProcCommand(strStoredProcedureName); dbCommand.CommandTimeout = DataHelper.CONNECTION_TIMEOUT; database.AddInParameter(dbCommand, "@MovingDetailID", DbType.String, objPropConsumer.ConsumerMovingDetailID); database.AddInParameter(dbCommand, "@FromZip", DbType.String, objPropConsumer.FromZipCode); database.AddInParameter(dbCommand, "@ToZip", DbType.String, objPropConsumer.ToZipCode); database.AddInParameter(dbCommand, "@MovingDate", DbType.DateTime, objPropConsumer.MoveDate); database.AddInParameter(dbCommand, "@PLServiceID", DbType.Int32, objPropConsumer.ServiceID); database.AddInParameter(dbCommand, "@FromAreaCode", DbType.String, pFromAreaCode); database.AddInParameter(dbCommand, "@FromState", DbType.String, pFromState); database.AddInParameter(dbCommand, "@ToAreaCode", DbType.String, pToAreaCode); database.AddInParameter(dbCommand, "@ToState", DbType.String, pToState); DataSet dstSearchResult = new DataSet("MoverSearchResult"); database.LoadDataSet(dbCommand, dstSearchResult, new string[] { "MoverSearchResult" });

    Read the article

  • TCP Socket.Connect is generating false positives

    - by Mark
    I'm experiencing really weird behavior with the Socket.Connect method in C#. I am attempting a TCP Socket.Connect to a valid IP but closed port and the method is continuing as if I have successfully connected. When I packet sniffed what was going on I saw that the app was receiving RST packets from the remote machine. Yet from the tracing that is in place it is clear that the connect method is not throwing an exception. Any ideas what might be causing this? The code that is running is basically this IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Parse(m_ipAddress), m_port); Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpSocket.Connect(iep); To add to the mystery... when running this code in a stand alone console application, the result is as expected – the connect method throws an exception. However, when running it in the Windows Service deployment we have the connect method does not throw an exception. Edit in response to Mystere Man's answer How would the exception be swallowed? I have a Trace.WriteLine right above the .Connect method and a Trace.WriteLine right under it (not shown in the code sample for readability). I know that both traces are running. I also have a try catch around the whole thing which also does a Trace.Writeline and I don't see that in the log files anywhere. I have also enabled the internal socket tracing as you suggested. I don't see any exceptions. I see what appears to be successful connections. I am trying to identify differences between the windows service app and the diagnostic console app I made. I am running out of ideas though End edit Thanks

    Read the article

  • Groovy htmlunit getFirstByXPath returning null

    - by StartingGroovy
    I have had a few issues with HtmlUnit returning nulls lately and am looking for guidance. each of my results for grabbing the first row of a website have returned null. I am wondering if someone can A) explain why they might be returning null B) explain better ways (if there are some) to go about getting the information Here is my current code (URL is in the source): client = new WebClient(BrowserVersion.FIREFOX_3) client.javaScriptEnabled = false def url = "http://www.hidemyass.com/proxy-list/" page = client.getPage(url) IpAddress = page.getFirstByXPath("//html/body/div/div/form/table/tbody/tr/td[2]").getValue() println "IP Address is: $data" //returns null //Port_Number is an Image Country = page.getFirstByXPath("//html/body/div/div/form/table/tbody/tr/td[4][@class='country']/@rel").getValue() println "Country abbreviation is: $Country" //differentiate speed and connection by name of gif? Type = page.getFirstByXPath("//html/body/div/div/form/table/tbody/tr/td[7]").getValue() println "Proxy type is: $Type" Anonymity = page.getFirstByXPath("//html/body/div/div/form/table/tbody/tr/td[8]").getValue() println "Anonymity Level is: $Anonymity" client.closeAllWindows() Right now all of my XPaths return null and .getValue() obviously doesn't work on null. I also have questions as to what I should do about the PORT since it is an image? Is there a better alternative than downloading it and attempting to solve it by OCR? Side Note There is no significance in this site, I was just looking for a site that I could practice scraping on (the last one I ran into issues of fragment identities and couldn't get an answer to: HtmlUnit getByXpath returns null and HtmlUnit and Fragment Identities )

    Read the article

  • Paramiko ssh output stops at --more--

    - by Anesh
    The output stops printing at --more-- any idea how to get the end of the output >>> import paramiko >>> ssh = paramiko.SSHClient() >>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) >>> conn=ssh.connect("ipaddress",username="user", password="pass") >>> channel = ssh.invoke_shell() >>> channel.send("en\n") 3 >>> channel.send("password\n") 9 >>> channel.send("show security local-user-list\n") 30 >>> results = '' >>> channel.send("\n") 1 >>> results += channel.recv(5000) >>> print results bluecoat>en Password: bluecoat#show security local-user-list Default List: local_user_database Append users loaded from file to default list: false local_user_database Lockout parameters: Max failed attempts: 60 Lockout duration: 3600 Reset interval: 7200 Users: Groups: admin_local Lockout parameters: Max failed attempts: 60 Lockout duration: 3600 Reset interval: 7200 Users: <username> Hashed Password: Enabled: true Groups: <username> Hashed Password: Enabled: true **--More--** As you can see above the output stops printing at --more-- any idea how to get the output to print till the end.

    Read the article

  • How can i get a file from remote machine?

    - by programmerist
    How can i get a file from remote computer? i know remote computer ip and 51124 port is open. i need this algorith: 1) Connect 192.xxx.x.xxx ip via 51124 port 2) filename:123456 (i want to search it on remote machine) 3) Get File 4) Save C:\ 51124 port is open. can i access and can i search any file according to filename? My code is below: IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 51124); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); sock.Bind(ipEnd); sock.Listen(maxConnections); Socket serverSocket = sock.Accept(); byte[] data = new byte[bufferSize]; int received = serverSocket.Receive(data); int filenameLength = BitConverter.ToInt32(data, 0); string filename = Encoding.ASCII.GetString(data, 4, filenameLength); BinaryWriter bWrite = new BinaryWriter(File.Open(outPath + filename, FileMode.Create)); bWrite.Write(data, filenameLength + 4, received - filenameLength - 4); int received2 = serverSocket.Receive(data); while (received2 0) { bWrite.Write(data, 0, received2); received2 = serverSocket.Receive(data); } bWrite.Close(); serverSocket.Close(); sock.Close();

    Read the article

  • WMI to reboot remote machine

    - by Stephen Murby
    I found this code on an old thread to shutdown the local machine: using System.Management; void Shutdown() { ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); mcWin32.Get(); // You can't shutdown without security privileges mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); // Flag 1 means we want to shut down the system. Use "2" to reboot. mboShutdownParams["Flags"] = "1"; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } Is it possible to use a similar WMI method to reboot flag"2" a remote machine, for which i only have machine name, not IPaddress. EDIT: I currently have; SearchResultCollection allMachinesCollected = machineSearch.FindAll(); Methods myMethods = new Methods(); string pcName; ArrayList allComputers = new ArrayList(); foreach (SearchResult oneMachine in allMachinesCollected) { //pcName = oneMachine.Properties.PropertyNames.ToString(); pcName = oneMachine.Properties["name"][0].ToString(); allComputers.Add(pcName); MessageBox.Show(pcName + "has been sent the restart command."); Process.Start("shutdown.exe", "-r -f -t 0 -m \" + pcName); } but this doesn't work, and i would prefer WMI going forward.

    Read the article

  • Concurrent connections in C# socket

    - by Chu Mai
    There are three apps run at the same time, 2 clients and 1 server. The whole system should function as following: The client sends an serialized object to server then server receives that object as a stream, finally the another client get that stream from server and deserialize it. This is the sender: TcpClient tcpClient = new TcpClient(); tcpClient.Connect("127.0.0.1", 8888); Stream stream = tcpClient.GetStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(stream, event); // Event is the sending object tcpClient.Close(); Server code: TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888); listener.Start(); Console.WriteLine("Server is running at localhost port 8888 "); while (true) { Socket socket = listener.AcceptSocket(); try { Stream stream = new NetworkStream(socket); // Typically there should be something to write the stream // But I don't knwo exactly what should the stream write } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); Console.WriteLine("Disconnected: {0}", socket.RemoteEndPoint); } } The receiver: TcpClient client = new TcpClient(); // Connect the client to the localhost with port 8888 client.Connect("127.0.0.1", 8888); Stream stream = client.GetStream(); Console.WriteLine(stream); when I run only the sender and server, and check the server, server receives correctly the data. The problem is when I run the receiver, everything is just disconnected. So where is my problem ? Could anyone point me out ? Thanks

    Read the article

  • Adding different objects to array, but only one object repeating

    - by Carpetfizz
    I have a small piece of PHP code that goes through valid values and fetches information about them. It then pushes it to an array. For some reason, I'm only getting the last item of $row, repeated several times. When I try to print_r at #1 in the code, the expected values are outputted. However, at the end of the loop, or outside of it, when I try to print_r($ipArray), I'm only getting the last value repeated multiple times. Any help would be much appreciated! while($row = mysqli_fetch_array($getIpQuery, MYSQLI_NUM)){ for($x=0;$x<count($row);$x++) { $getIpInfo = mysqli_query($dbcon, "SELECT * FROM ipInfo WHERE address='$row[$x]'"); $retrievedInfo = mysqli_fetch_array($getIpInfo, MYSQLI_NUM); $ipInfo->ipAddress = $retrievedInfo[0]; $ipInfo->portNum = $retrievedInfo[1]; print_r($ipInfo); //#1: Works perfectly fine. array_push($ipArray,$ipInfo); } } print_r($ipArray); //this is where I'm getting an output of only the last element of `$row`. Thanks! ~Carpetfizz

    Read the article

  • OpenSSH does not accept public key?

    - by Bob
    I've been trying to solve this for a while, but I'm admittedly quite stumped. I just started up a new server and was setting up OpenSSH to use key-based SSH logins, but I've run into quite a dilemma. All the guides are relatively similar, and I was following them closely (despite having done this once before). I triple checked my work to see if I would notice some obvious screw up - but nothing is apparent. As far as I can tell, I haven't done anything wrong (and I've checked very closely). If it's any help, on my end I'm using Cygwin and the server is running Ubuntu 12.04.1 LTS. Anyways, here is the output (I've removed/censored some parts for privacy (primarily anything with my name, website, or its IP address), but I can assure you that nothing is wrong there): $ ssh user@host -v OpenSSH_5.9p1, OpenSSL 0.9.8r 8 Feb 2011 debug1: Connecting to host [ipaddress] port 22. debug1: Connection established. debug1: identity file /home/user/.ssh/id_rsa type 1 debug1: identity file /home/user/.ssh/id_rsa-cert type -1 debug1: identity file /home/user/.ssh/id_dsa type -1 debug1: identity file /home/user/.ssh/id_dsa-cert type -1 debug1: identity file /home/user/.ssh/id_ecdsa type -1 debug1: identity file /home/user/.ssh/id_ecdsa-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1 debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.9 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-ctr hmac-md5 none debug1: kex: client->server aes128-ctr hmac-md5 none debug1: sending SSH2_MSG_KEX_ECDH_INIT debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ECDSA 24:68:c3:d8:13:f8:61:94:f2:95:34:d1:e2:6d:e7:d7 debug1: Host 'host' is known and matches the ECDSA host key. debug1: Found key in /home/user/.ssh/known_hosts:2 debug1: ssh_ecdsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Offering RSA public key: /home/user/.ssh/id_rsa debug1: Authentications that can continue: publickey debug1: Trying private key: /home/user/.ssh/id_dsa debug1: Trying private key: /home/user/.ssh/id_ecdsa debug1: No more authentication methods to try. Permission denied (publickey). What can I do to resolve my problem?

    Read the article

  • Two VHosts Use Same DocumentRoot, PHP Not Working on Second VHost

    - by thegrip
    I'm helping maintain an e-commerce site that is run on Magento. This site is an outlet for our wholesale customers. We have recently decided to open a second store to reach out to our Retail customers. We decided to set up another website inside of our magento store so that we can share the products across both stores. I'm in the process of setting up this new site on the server, but have run into an issue. I've set up the second vhost for the new retail site, and I've made the DocumentRoot for this vhost the same as for the wholesale site, so we can use one magento application for both sites. This is where the error occurs. When I browse to the new store it triggers a download of the index.php file. So I know the DocumentRoot directive is working, but it seems like PHP is being broken in the process. I'm using plesk to manage the server. I've made sure that PHP is turned on in both vhosts and still get the same issue. Does this sound like a problem of PHP breaking, or is it possible my vhost.conf file is set up incorrectly? (Although the vhost is managed by plesk and appears correct) Any help will be much appreciated. EDIT: Here's the vhost configs (generated by plesk): <VirtualHost IPADDRESS:80> ServerName domain.com:80 ServerAdmin "[email protected]" DocumentRoot /var/www/vhosts/domain.com/subdomains/tk/httpdocs CustomLog /var/www/vhosts/domain.com/statistics/logs/access_log plesklog ErrorLog /var/www/vhosts/domain.com/statistics/logs/error_log <IfModule mod_ssl.c> SSLEngine off </IfModule> <Directory /var/www/vhosts/domain.com/subdomains/tk/httpdocs> <IfModule mod_php4.c> php_admin_flag engine on php_admin_flag safe_mode off php_admin_value open_basedir "/var/www/vhosts/domain.com/subdomains/tk/httpdocs:/tmp" </IfModule> <IfModule mod_php5.c> php_admin_flag engine on php_admin_flag safe_mode off php_admin_value open_basedir "/var/www/vhosts/mkdesigngroup.com/subdomains/tk/httpdocs:/tmp" </IfModule> Options -Includes -ExecCGI </Directory> Include /var/www/vhosts/domain.com/subdomains/tk/conf/vhost.conf And here's what I've added in vhost.conf (which is included by plesk): DocumentRoot /var/www/vhosts/domain.com/subdomains/dev/httpdocs -grip

    Read the article

  • Reading a POP3 server with only TcpClient and StreamWriter/StreamReader[SOLVED]

    - by WebDevHobo
    I'm trying to read mails from my live.com account, via the POP3 protocol. I've found the the server is pop3.live.com and the port if 995. I'm not planning on using a pre-made library, I'm using NetworkStream and StreamReader/StreamWriter for the job. I need to figure this out. So, any of the answers given here: http://stackoverflow.com/questions/44383/reading-email-using-pop3-in-c are not usefull. It's part of a larger program, but I made a small test to see if it works. Eitherway, i'm not getting anything. Here's the code I'm using, which I think should be correct. EDIT: this code is old, please refer to the second block problem solved. public Program() { string temp = ""; using(TcpClient tc = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),8000))) { tc.Connect("pop3.live.com",995); using(NetworkStream nws = tc.GetStream()) { using(StreamReader sr = new StreamReader(nws)) { using(StreamWriter sw = new StreamWriter(nws)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); while(temp != ".") { temp += sr.ReadLine(); } } } } } Console.WriteLine(temp); } Visual Studio debugger constantly falls over tc.Connect("pop3.live.com",995); Which throws an "A socket operation was attempted to an unreachable network 65.55.172.253:995" error. So, I'm sending from port 8000 on my machine to port 995, the hotmail pop3 port. And I'm getting nothing, and I'm out of ideas. Second block: Problem was apparently that I didn't write the quit command. The Code: public Program() { string str = string.Empty; string strTemp = string.Empty; using(TcpClient tc = new TcpClient()) { tc.Connect("pop3.live.com",995); using(SslStream sl = new SslStream(tc.GetStream())) { sl.AuthenticateAsClient("pop3.live.com"); using(StreamReader sr = new StreamReader(sl)) { using(StreamWriter sw = new StreamWriter(sl)) { sw.WriteLine("USER " + user); sw.Flush(); sw.WriteLine("PASS " + pass); sw.Flush(); sw.WriteLine("LIST"); sw.Flush(); sw.WriteLine("QUIT "); sw.Flush(); while((strTemp = sr.ReadLine()) != null) { if(strTemp == "." || strTemp.IndexOf("-ERR") != -1) { break; } str += strTemp; } } } } } Console.WriteLine(str); }

    Read the article

  • TcpListener is queuing connections faster than I can clear them

    - by Matthew Brindley
    As I understand it, TcpListener will queue connections once you call Start(). Each time you call AcceptTcpClient (or BeginAcceptTcpClient), it will dequeue one item from the queue. If we load test our TcpListener app by sending 1,000 connections to it at once, the queue builds far faster than we can clear it, leading (eventually) to timeouts from the client because it didn't get a response because its connection was still in the queue. However, the server doesn't appear to be under much pressure, our app isn't consuming much CPU time and the other monitored resources on the machine aren't breaking a sweat. It feels like we're not running efficiently enough right now. We're calling BeginAcceptTcpListener and then immediately handing over to a ThreadPool thread to actually do the work, then calling BeginAcceptTcpClient again. The work involved doesn't seem to put any pressure on the machine, it's basically just a 3 second sleep followed by a dictionary lookup and then a 100 byte write to the TcpClient's stream. Here's the TcpListener code we're using: // Thread signal. private static ManualResetEvent tcpClientConnected = new ManualResetEvent(false); public void DoBeginAcceptTcpClient(TcpListener listener) { // Set the event to nonsignaled state. tcpClientConnected.Reset(); listener.BeginAcceptTcpClient( new AsyncCallback(DoAcceptTcpClientCallback), listener); // Wait for signal tcpClientConnected.WaitOne(); } public void DoAcceptTcpClientCallback(IAsyncResult ar) { // Get the listener that handles the client request, and the TcpClient TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); if (inProduction) ThreadPool.QueueUserWorkItem(state => HandleTcpRequest(client, serverCertificate)); // With SSL else ThreadPool.QueueUserWorkItem(state => HandleTcpRequest(client)); // Without SSL // Signal the calling thread to continue. tcpClientConnected.Set(); } public void Start() { currentHandledRequests = 0; tcpListener = new TcpListener(IPAddress.Any, 10000); try { tcpListener.Start(); while (true) DoBeginAcceptTcpClient(tcpListener); } catch (SocketException) { // The TcpListener is shutting down, exit gracefully CheckBuffer(); return; } } I'm assuming the answer will be related to using Sockets instead of TcpListener, or at least using TcpListener.AcceptSocket, but I wondered how we'd go about doing that? One idea we had was to call AcceptTcpClient and immediately Enqueue the TcpClient into one of multiple Queue<TcpClient> objects. That way, we could poll those queues on separate threads (one queue per thread), without running into monitors that might block the thread while waiting for other Dequeue operations. Each queue thread could then use ThreadPool.QueueUserWorkItem to have the work done in a ThreadPool thread and then move onto dequeuing the next TcpClient in its queue. Would you recommend this approach, or is our problem that we're using TcpListener and no amount of rapid dequeueing is going to fix that?

    Read the article

  • System.Net.Dns.GetHostAddresses("")

    - by dbasnett
    Yesterday s**ked, and today ain't (sic) looking better. I have an application I have been working on and it can be slow to start when my ISP is down because of DNS. My ISP was down for 3 hours yesterday, so I didn't think much about this piece of code I had added, until I found that it is always slow to start. This code is supposed to return your IP address and my reading of the link suggests that should be immediate, but it isn't, at least on my machine. Oh, and yesterday before the internet went down, I upgraded (oymoron) to XP SP3, and have had other problems. So my questions / request: 1. Am I doing this right? 2. If you run this on your machine does it take 39 seconds to return your IP address? It does on mine. One other note, I did a packet capture and the first request did NOT go on the wire, but the second did, and was answered quickly. So the question is what happened in XP SP3 that I am missing, besides a brain. One last note. If I resolve a FQDN all is well. Public Class Form1 'http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx ' 'excerpt 'The GetHostAddresses method queries a DNS server 'for the IP addresses associated with a host name. ' 'If hostNameOrAddress is an IP address, this address 'is returned without querying the DNS server. ' 'When an empty string is passed as the host name, 'this method returns the IPv4 addresses of the local host Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim stpw As New Stopwatch stpw.Reset() stpw.Start() 'originally Dns.GetHostEntry, but slow also Dim myIPs() As System.Net.IPAddress = System.Net.Dns.GetHostAddresses("") stpw.Stop() Debug.WriteLine("'" & stpw.Elapsed.TotalSeconds) If myIPs.Length > 0 Then Debug.WriteLine("'" & myIPs(0).ToString) 'debug '39.8990525 '192.168.1.2 stpw.Reset() stpw.Start() 'originally Dns.GetHostEntry, but slow also myIPs = System.Net.Dns.GetHostAddresses("www.vbforums.com") stpw.Stop() Debug.WriteLine("'" & stpw.Elapsed.TotalSeconds) If myIPs.Length > 0 Then Debug.WriteLine("'" & myIPs(0).ToString) 'debug '0.042212 '63.236.73.220 End Sub End Class

    Read the article

  • C# Detect Localhost Port Usage

    - by ThaKidd
    In advance, thank you for your advice. I am currently working on a program which uses Putty to create a SSH connection with a server that uses local port forwarding to enable a client, running my software, to access the service behind the SSH server via localhost. IE: client:20100 - Internet - Remote SSH server exposed via router/firewall - Local Intranet - Intranet Web POP3 Server:110. Cmd Line: "putty -ssh -2 -P 22 -C -L 20100:intranteIP:110 -pw sshpassword sshusername@sshserver" Client would use putty to create a SSH connection with the SSH server specifying in the connection string that it would like to tie port 110 of the Intranet POP3 Server to port 20100 on the client system. Therefore the client would be able to open up a mail client to localhost:20100 and interact with the Internal POP3 server over the SSH tunnel. The above is a general description. I already know what I am trying to do will work without a problem so am not looking for debate on the above. The question is this...How can I ensure the local port (I cannot use dynamic ports, so it must be static) on localhost is not being used or listened to by any other application? I am currently executing this code in my C# app: private bool checkPort(int port) { try { //Create a socket on the current IPv4 address Socket TestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create an IP end point IPEndPoint localIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); // Bind that port TestSocket.Bind(localIP); // Cleanup TestSocket.Close(); return false; } catch (Exception e) { // Exception occurred. Port is already bound. return true; } } I am currently calling this function starting with a specific port in a for loop to get the 'false' return at the first available port. The first port I try is actually being listened to by uTorrent. The above code does not catch this and my connection fails. What is the best method to ensure a port is truly free? I do understand some other program may grab the port during/after I have tested it. I just need to find something that will ensure it is not currently in use AT ALL when the test is executed. If there is a way to truly reserve the localhost port during the test, I would love to hear about it.

    Read the article

  • Problem with tcp server when converting to service

    - by djerry
    Hello lads, I'm working on monitoring some object (cdr-packets). I'm setting up a tcp-server and am listening on port 50043 for the packages. The program as a console application is working just fine, my server is working like it should and i'm receiving the packets. When i try to use it as a service, i cannot seem to get a client connected to my server. Is there something i need to change to deploy this as a service? Code below is from my application: this is my service class where i start protected override void OnStart(string[] args) { server = new TcpServer(); server.StartServer(); } this is the constructor of TcpServer public TcpServer() { try { _server = new TcpListener(IPAddress.Any, 50043); } catch (Exception) { _server = null; } } this is the method i call after initialising the class public void StartServer() { if (_server != null) { // Create a ArrayList for storing SocketListeners before starting the server. _socketListenersList = new ArrayList(); // Start the Server and start the thread to listen client requests. _server.Start(); _serverThread = new Thread(new ThreadStart(ServerThreadStart)); _serverThread.Start(); // Create a low priority thread that checks and deletes client // SocktConnection objcts that are marked for deletion. _purgingThread = new Thread(new ThreadStart(PurgingThreadStart)); _purgingThread.Priority = ThreadPriority.Lowest; _purgingThread.Start(); } } this is the thread that keep checking if any client tries to connect private void ServerThreadStart() { // Client Socket variable; Socket clientSocket = null; TcpSocketListener socketListener = null; while (!_stopServer) { try { // Wait for any client requests and if there is any request from any //client accept it (Wait indefinitely). clientSocket = _server.AcceptSocket(); // Create a SocketListener object for the client. socketListener = new TcpSocketListener(clientSocket); // Add the socket listener to an array list in a thread safe fashon. lock (_socketListenersList) { _socketListenersList.Add(socketListener); } // Start a communicating with the client in a different thread. socketListener.StartSocketListener(); } catch (SocketException se) { _stopServer = true; } } } when for the first time a packet waits to be read, and i get to "clientSocket = _server.AcceptSocket();", it throws an exception (service, not very good debugable) Does anyone recognize this problem or can help me? Thanks in advance

    Read the article

  • How a database is loaded into an application?

    - by Audel
    Hi All i need is a simple explanation on how does this function work I also attached a piece of php which I think is the one that retrieves the data from the database. Please correct me if I'm wrong Cheers. function loadDatabaseRecords () { // Mozilla/Safari if (window.XMLHttpRequest) { xmlHttpReq = new XMLHttpRequest(); } // IE else if (window.ActiveXObject) { xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } alert ("To Server (Load Records):\n\najax-open-DB.php"); xmlHttpReq.open('GET', "ajax-open-DB.php", true); xmlHttpReq.onreadystatechange = loadDatabaseRecordsCallback; xmlHttpReq.send(null); } <?php $link = mysql_connect ("ipaddress", "localhost", "password"); mysql_select_db ("database1"); $query = "SELECT * from addressbook"; $result = mysql_query ($query); print "<table>"; print "<tr>"; print "<th>Firstname</th><th>Lastname</th><th>Address</th><th>Telephone</th>"; print "</tr>"; for ($i = 0; $i < mysql_num_rows ($result); $i ++) { $row = mysql_fetch_object ($result); print "<tr>"; print "<td>$row->firstname</td>"; print "<td>$row->lastname</td>"; print "<td>$row->address</td>"; print "<td>$row->telephone</td>"; print "</tr>"; } print "</table>"; mysql_close ($link); ?>

    Read the article

  • Remote Desktop failed logon event 4625 not logging correctly on 2008 Terminal Services server

    - by Zone12
    When I use the new remote desktop with ssl and try to log on with bad credentials it logs a 4625 event as expected. The problem is, it doesn't log the ip address, so I can't block malicious logons in our firewall. The event looks like this: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{00000000-0000-0000-0000-000000000000}" /> <EventID>4625</EventID> <Version>0</Version> <Level>0</Level> <Task>12544</Task> <Opcode>0</Opcode> <Keywords>0x8010000000000000</Keywords> <TimeCreated SystemTime="2012-04-13T06:52:36.499113600Z" /> <EventRecordID>467553</EventRecordID> <Correlation /> <Execution ProcessID="544" ThreadID="596" /> <Channel>Security</Channel> <Computer>ontheinternet</Computer> <Security /> </System> <EventData> <Data Name="SubjectUserSid">S-1-0-0</Data> <Data Name="SubjectUserName">-</Data> <Data Name="SubjectDomainName">-</Data> <Data Name="SubjectLogonId">0x0</Data> <Data Name="TargetUserSid">S-1-0-0</Data> <Data Name="TargetUserName">notauser</Data> <Data Name="TargetDomainName">MYSERVER-PC</Data> <Data Name="Status">0xc000006d</Data> <Data Name="FailureReason">%%2313</Data> <Data Name="SubStatus">0xc0000064</Data> <Data Name="LogonType">3</Data> <Data Name="LogonProcessName">NtLmSsp</Data> <Data Name="AuthenticationPackageName">NTLM</Data> <Data Name="WorkstationName">MYSERVER-PC</Data> <Data Name="TransmittedServices">-</Data> <Data Name="LmPackageName">-</Data> <Data Name="KeyLength">0</Data> <Data Name="ProcessId">0x0</Data> <Data Name="ProcessName">-</Data> <Data Name="IpAddress">-</Data> <Data Name="IpPort">-</Data> </EventData> </Event> It seems because the logon type is 3 and not 10 like the old rdp sessions, the ip address and other information is not stored. The machine I am trying to connect from is on the internet and not on the same network as the server. Does anyone know where this information is stored (and what other events are generated with a failed logon)? Any help will be much appreciated.

    Read the article

  • WIN32_NetworkAdapterConfiguration does not report IP from PPP adapter

    - by Michael
    On a Windows 7 device, the following WMI query does not report back an enabled PPP adapter: Select Index,MACAddress,IPAddress,IPSubnet,DefaultIPGateway,DNSServerSearchOrder from Win32_NetworkAdapterConfiguration where IPEnabled=true Where ipconfig gives you all the information correctly: Windows IP Configuration PPP adapter XYZ VPN: Connection-specific DNS Suffix . : IPv4 Address. . . . . . . . . . . : 123.456.789.123 Subnet Mask . . . . . . . . . . . : 255.255.255.255 Default Gateway . . . . . . . . . : 0.0.0.0 Wireless LAN adapter Wireless Network Connection: Connection-specific DNS Suffix . : IPv4 Address. . . . . . . . . . . : 192.168.178.11 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.178.1 Ethernet adapter Local Area Connection 3: Media State . . . . . . . . . . . : Media disconnected Connection-specific DNS Suffix . : Any ideas how I can script this by using WMI or VBS?

    Read the article

  • MacBook Pro 10.6 losing dns service, network connection still functional if you know the ip address.

    - by Vincent
    MacBook pro connected to a wireless network (not sure about wired) I lose DNS. I still have a functioning connection and as long as I know the ip address of the website, server... for example skype works, ssh name@ipaddress, .... Things can be working properly and then just quit, Once I was im via skype and lost dns skype continued to work. This has happened in multiple locations on private and public networks. What does not work/fix it: Resetting router changing dns server on computer or router connecting to another network removing the airport interface and adding it back flushing dns The only solution seems to be a restart. A solution to this would be great, but any ideas of this to try would be great. Even a sure way to reproduce this would be useful. Maybe related question: But this is most definitely not true for me. "if I refresh enough -- 3 to 4 times --, it will usually pull up the site. " Here are some tests from terminal. Basically this confirms dns in not functioning vmd17:~ vmd$ ping google.com ping: cannot resolve google.com: Unknown host Trace route to google dns, This works vmd17:~ vmd$ /usr/sbin/traceroute -n -w 2 -q 2 -m 30 8.8.8.8 traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 52 byte packets 1 192.168.1.1 5.195 ms 2.519 ms 2 67.172.136.1 31.881 ms 9.177 ms 3 68.85.107.121 12.168 ms 10.003 ms 4 68.86.103.41 12.021 ms 9.594 ms 5 68.86.91.1 16.712 ms 12.837 ms 6 68.86.86.210 29.951 ms 25.826 ms 7 68.86.87.218 29.554 ms 42.894 ms 8 75.149.231.70 68.271 ms 68.362 ms 9 72.14.233.77 141.178 ms 72.14.233.85 82.553 ms 10 72.14.238.243 83.381 ms 82.811 ms 11 72.14.232.213 194.387 ms 72.14.232.215 84.837 ms 12 209.85.253.145 100.294 ms * 13 8.8.8.8 101.689 ms 89.694 ms 208.67.222.22 is the ip address of opendns dns server vmd17:~ vmd$ dig @208.67.222.222 8.8.8.8 ; <<>> DiG 9.6.0-APPLE-P2 <<>> @208.67.222.222 8.8.8.8 ; (1 server found) ;; global options: +cmd ;; connection timed out; no servers could be reached vmd17:~ vmd$ dig @208.67.222.222 gogle.com vmd17:~ vmd$ dig @208.67.222.222 google.com ; <<>> DiG 9.6.0-APPLE-P2 <<>> @208.67.222.222 google.com ; (1 server found) ;; global options: +cmd ;; connection timed out; no servers could be reached vmd17:~ vmd$ dig @8.8.8.8 google.com ; <<>> DiG 9.6.0-APPLE-P2 <<>> @8.8.8.8 google.com ; (1 server found) ;; global options: +cmd ;; connection timed out; no servers could be reached

    Read the article

  • OpenVPN on ec2 bridged mode connects but no Ping, DNS or forwarding

    - by michael
    I am trying to use OpenVPN to access the internet over a secure connection. I have openVPN configured and running on Amazon EC2 in bridge mode with client certs. I can successfully connect from the client, but I cannot get access to the internet or ping anything from the client I checked the following and everything seems to shows a successful connection between the vpn client/server and UDP traffic on 1194 [server] sudo tcpdump -i eth0 udp port 1194 (shows UDP traffic after establishing connection) [server] sudo iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all -- anywhere anywhere ACCEPT all -- anywhere anywhere Chain FORWARD (policy ACCEPT) target prot opt source destination ACCEPT all -- anywhere anywhere Chain OUTPUT (policy ACCEPT) target prot opt source destination [server] sudo iptables -L -t nat Chain PREROUTING (policy ACCEPT) target prot opt source destination Chain POSTROUTING (policy ACCEPT) target prot opt source destination MASQUERADE all -- ip-W-X-Y-0.us-west-1.compute.internal/24 anywhere Chain OUTPUT (policy ACCEPT) target prot opt source destination [server] openvpn.log Wed Oct 19 03:11:26 2011 localhost/a.b.c.d:61905 [localhost] Inactivity timeout (--ping-restart), restarting Wed Oct 19 03:11:26 2011 localhost/a.b.c.d:61905 SIGUSR1[soft,ping-restart] received, client-instance restarting Wed Oct 19 03:41:31 2011 MULTI: multi_create_instance called Wed Oct 19 03:41:31 2011 a.b.c.d:57889 Re-using SSL/TLS context Wed Oct 19 03:41:31 2011 a.b.c.d:57889 LZO compression initialized Wed Oct 19 03:41:31 2011 a.b.c.d:57889 Control Channel MTU parms [ L:1574 D:166 EF:66 EB:0 ET:0 EL:0 ] Wed Oct 19 03:41:31 2011 a.b.c.d:57889 Data Channel MTU parms [ L:1574 D:1450 EF:42 EB:135 ET:32 EL:0 AF:3/1 ] Wed Oct 19 03:41:31 2011 a.b.c.d:57889 Local Options hash (VER=V4): '360696c5' Wed Oct 19 03:41:31 2011 a.b.c.d:57889 Expected Remote Options hash (VER=V4): '13a273ba' Wed Oct 19 03:41:31 2011 a.b.c.d:57889 TLS: Initial packet from [AF_INET]a.b.c.d:57889, sid=dd886604 ab6ebb38 Wed Oct 19 03:41:35 2011 a.b.c.d:57889 VERIFY OK: depth=1, /C=US/ST=CA/L=SanFrancisco/O=EXAMPLE/CN=EXAMPLE_CA/[email protected] Wed Oct 19 03:41:35 2011 a.b.c.d:57889 VERIFY OK: depth=0, /C=US/ST=CA/L=SanFrancisco/O=EXAMPLE/CN=localhost/[email protected] Wed Oct 19 03:41:37 2011 a.b.c.d:57889 Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key Wed Oct 19 03:41:37 2011 a.b.c.d:57889 Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication Wed Oct 19 03:41:37 2011 a.b.c.d:57889 Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key Wed Oct 19 03:41:37 2011 a.b.c.d:57889 Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication Wed Oct 19 03:41:37 2011 a.b.c.d:57889 Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 1024 bit RSA Wed Oct 19 03:41:37 2011 a.b.c.d:57889 [localhost] Peer Connection Initiated with [AF_INET]a.b.c.d:57889 Wed Oct 19 03:41:39 2011 localhost/a.b.c.d:57889 PUSH: Received control message: 'PUSH_REQUEST' Wed Oct 19 03:41:39 2011 localhost/a.b.c.d:57889 SENT CONTROL [localhost]: 'PUSH_REPLY,redirect-gateway def1 bypass-dhcp,route-gateway W.X.Y.Z,ping 10,ping-restart 120,ifconfig W.X.Y.Z 255.255.255.0' (status=1) Wed Oct 19 03:41:40 2011 localhost/a.b.c.d:57889 MULTI: Learn: (IPV6) -> localhost/a.b.c.d:57889 [client] tracert google.com Tracing route to google.com [74.125.71.104] over a maximum of 30 hops: 1 347 ms 349 ms 348 ms PC [w.X.Y.Z] 2 * * * Request timed out. I can also successfully ping the server IP address from the client, and ping google.com from an SSH shell on the server. What am I doing wrong? Here is my config (Note: W.X.Y.Z == amazon EC2 private ipaddress) bridge config on br0 ifconfig eth0 0.0.0.0 promisc up brctl addbr br0 brctl addif br0 eth0 ifconfig br0 W.X.Y.X netmask 255.255.255.0 broadcast W.X.Y.255 up route add default gw W.X.Y.1 br0 /etc/openvpn/server.conf (from https://help.ubuntu.com/10.04/serverguide/C/openvpn.html) local W.X.Y.Z dev tap0 up "/etc/openvpn/up.sh br0" down "/etc/openvpn/down.sh br0" ;server W.X.Y.0 255.255.255.0 server-bridge W.X.Y.Z 255.255.255.0 W.X.Y.105 W.X.Y.200 ;push "route W.X.Y.0 255.255.255.0" push "redirect-gateway def1 bypass-dhcp" push "dhcp-option DNS 208.67.222.222" push "dhcp-option DNS 208.67.220.220" tls-auth ta.key 0 # This file is secret user nobody group nogroup log-append openvpn.log iptables config sudo iptables -A INPUT -i tap0 -j ACCEPT sudo iptables -A INPUT -i br0 -j ACCEPT sudo iptables -A FORWARD -i br0 -j ACCEPT sudo iptables -t nat -A POSTROUTING -s W.X.Y.0/24 -o eth0 -j MASQUERADE echo 1 > /proc/sys/net/ipv4/ip_forward Routing Tables added route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface W.X.Y.0 0.0.0.0 255.255.255.0 U 0 0 0 br0 0.0.0.0 W.X.Y.1 0.0.0.0 UG 0 0 0 br0 C:>route print =========================================================================== Interface List 32...00 ff ac d6 f7 04 ......TAP-Win32 Adapter V9 15...00 14 d1 e9 57 49 ......Microsoft Virtual WiFi Miniport Adapter #2 14...00 14 d1 e9 57 49 ......Realtek RTL8191SU Wireless LAN 802.11n USB 2.0 Net work Adapter 10...00 1f d0 50 1b ca ......Realtek PCIe GBE Family Controller 1...........................Software Loopback Interface 1 11...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface 16...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter 17...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2 18...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3 36...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #5 =========================================================================== IPv4 Route Table =========================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 10.1.2.1 10.1.2.201 25 10.1.2.0 255.255.255.0 On-link 10.1.2.201 281 10.1.2.201 255.255.255.255 On-link 10.1.2.201 281 10.1.2.255 255.255.255.255 On-link 10.1.2.201 281 127.0.0.0 255.0.0.0 On-link 127.0.0.1 306 127.0.0.1 255.255.255.255 On-link 127.0.0.1 306 127.255.255.255 255.255.255.255 On-link 127.0.0.1 306 224.0.0.0 240.0.0.0 On-link 127.0.0.1 306 224.0.0.0 240.0.0.0 On-link 10.1.2.201 281 255.255.255.255 255.255.255.255 On-link 127.0.0.1 306 255.255.255.255 255.255.255.255 On-link 10.1.2.201 281 =========================================================================== Persistent Routes: Network Address Netmask Gateway Address Metric 0.0.0.0 0.0.0.0 10.1.2.1 Default =========================================================================== C:>tracert google.com Tracing route to google.com [74.125.71.147] over a maximum of 30 hops: 1 344 ms 345 ms 343 ms PC [W.X.Y.221] 2 * * * Request timed out.

    Read the article

  • Bandwidth Limit User

    - by user45611
    Hello, i'm saxtor i would like to know how to limit users bandwidth for 10gb per day however i dont want to limit them by ipaddress because if they where to go to an internet cafe the users at the cafe will be restricted with that quota, i need to log them via sockets, example the user request to download a file from http://localhost with there username and password, when they download the file sql will update there bandwidth they used, i have a script here but its not working my buffer doesnt work that rate when a user uses multiple connections thanks for the help!. /** * @author saxtor if you can improve this code email me @saxtorinc.com * @copyright 2010 / /* * CREATE TABLE IF NOT EXISTS max_traffic ( id int(255) NOT NULL AUTO_INCREMENT, limit int(255) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ; */ //SQL Connection [this is hackable for testing] date_default_timezone_set("America/Guyana"); mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("Quota") or die(mysql_error()); function quota($id) { $result = mysql_query("SELECT `limit` FROM max_traffic WHERE id='$id' ") or die(error_log(mysql_error()));; $row = mysql_fetch_array($result); return $row[0]; } function update_quota($id,$value) { $result = mysql_query("UPDATE `max_traffic` SET `limit`='$value' WHERE id='$id'") or die(mysql_error()); return $value; } if ( quota(1) != 0) $limit = quota(1); else $limit = 0; $multipart = false; //was a part of the file requested? (partial download) $range = $_SERVER["HTTP_RANGE"]; if ($range) { //pass client Range header to rapidshare // _insert($range); $cookie .= "\r\nRange: $range"; $multipart = true; header("X-UR-RANGE-Range: $range"); } $url = 'http://127.0.0.1/puppy.iso'; $filename = basename($url); //octet-stream + attachment = client always stores file header('Content-type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$filename.'"'); //always included so clients know this script supports resuming header("Accept-Ranges: bytes"); //awful hack to pass rapidshare the premium cookie $user_agent = ini_get("user_agent"); ini_set("user_agent", $user_agent . "\r\nCookie: enc=$cookie"); $httphandle = fopen($url, "r"); $headers = stream_get_meta_data($httphandle); $size = $headers["wrapper_data"][6]; $sizer = explode(' ',$size); $size = $sizer[1]; //let's check the return header of rapidshare for range / length indicators //we'll just pass these to the client foreach ($headers["wrapper_data"] as $header) { $header = trim($header); if (substr(strtolower($header), 0, strlen("content-range")) == "content-range") { // _insert($range); header($header); header("X-RS-RANGE-" . $header); $multipart = true; //content-range indicates partial download } elseif (substr(strtolower($header), 0, strlen("Content-Length")) == "content-length") { // _insert($range); header($header); header("X-RS-CL-" . $header); } } if ($multipart) header('HTTP/1.1 206 Partial Content'); flush(); $speed = 4128; $packet = 1; //this is private dont touch. $bufsize = 128; //this is private dont touch/ $bandwidth = 0; //this is private dont touch. while (!(connection_aborted() || connection_status() == 1) && $size > 0) { while (!feof($httphandle) && $size > 0) { if ($limit <= 0 ) $size = 0; if ( $size < $bufsize && $size != 0 && $limit != 0) { echo fread($httphandle,$size); $bandwidth += $size; } else { if( $limit != 0) echo fread($httphandle,$bufsize); $bandwidth += $bufsize; } $size -= $bufsize; $limit -= $bufsize; flush(); if ($speed > 0 && ($bandwidth > $speed*$packet*103)) { usleep(100000); $packet++; //update_quota(1,$limit); } error_log(update_quota(1,$limit)); $limit = quota(1); //if( $size <= 0 ) // exit; } fclose($httphandle); } exit; ?

    Read the article

  • Reading off a socket until end of line C#?

    - by Omar Kooheji
    I'm trying to write a service that listens to a TCP Socket on a given port until an end of line is recived and then based on the "line" that was received executes a command. I've followed a basic socket programming tutorial for c# and have come up with the following code to listen to a socket: public void StartListening() { _log.Debug("Creating Maing TCP Listen Socket"); _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, _port); _log.Debug("Binding to local IP Address"); _mainSocket.Bind(ipLocal); _log.DebugFormat("Listening to port {0}",_port); _mainSocket.Listen(10); _log.Debug("Creating Asynchronous callback for client connections"); _mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } public void OnClientConnect(IAsyncResult asyn) { try { _log.Debug("OnClientConnect Creating worker socket"); Socket workerSocket = _mainSocket.EndAccept(asyn); _log.Debug("Adding worker socket to list"); _workerSockets.Add(workerSocket); _log.Debug("Waiting For Data"); WaitForData(workerSocket); _log.DebugFormat("Clients Connected [{0}]", _workerSockets.Count); _mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null); } catch (ObjectDisposedException) { _log.Error("OnClientConnection: Socket has been closed\n"); } catch (SocketException se) { _log.Error("Socket Exception", se); } } public class SocketPacket { private System.Net.Sockets.Socket _currentSocket; public System.Net.Sockets.Socket CurrentSocket { get { return _currentSocket; } set { _currentSocket = value; } } private byte[] _dataBuffer = new byte[1]; public byte[] DataBuffer { get { return _dataBuffer; } set { _dataBuffer = value; } } } private void WaitForData(Socket workerSocket) { _log.Debug("Entering WaitForData"); try { lock (this) { if (_workerCallback == null) { _log.Debug("Initializing worker callback to OnDataRecieved"); _workerCallback = new AsyncCallback(OnDataRecieved); } } SocketPacket socketPacket = new SocketPacket(); socketPacket.CurrentSocket = workerSocket; workerSocket.BeginReceive(socketPacket.DataBuffer, 0, socketPacket.DataBuffer.Length, SocketFlags.None, _workerCallback, socketPacket); } catch (SocketException se) { _log.Error("Socket Exception", se); } } public void OnDataRecieved(IAsyncResult asyn) { SocketPacket socketData = (SocketPacket)asyn.AsyncState; try { int iRx = socketData.CurrentSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; _log.DebugFormat("Created Char array to hold incomming data. [{0}]",iRx+1); System.Text.Decoder decoder = System.Text.Encoding.UTF8.GetDecoder(); int charLength = decoder.GetChars(socketData.DataBuffer, 0, iRx, chars, 0); _log.DebugFormat("Read [{0}] characters",charLength); String data = new String(chars); _log.DebugFormat("Read in String \"{0}\"",data); WaitForData(socketData.CurrentSocket); } catch (ObjectDisposedException) { _log.Error("OnDataReceived: Socket has been closed. Removing Socket"); _workerSockets.Remove(socketData.CurrentSocket); } catch (SocketException se) { _log.Error("SocketException:",se); _workerSockets.Remove(socketData.CurrentSocket); } } This I thought was going to be a good basis for what I wanted to do, but the code I have appended the incoming characters to a text box one by one and didn't do anything with it. Which doesn't really work for what I want to do. My main issue is the decoupling of the OnDataReceived method from the Wait for data method. which means I'm having issues building a string (I would use a string builder but I can accept multiple connections so that doesn't really work. Ideally I'd like to look while listening to a socket until I see and end of line character and then call a method with the resulting string as a parameter. What's the best way to go about doing this.

    Read the article

  • Problem with socket communication between C# and Flex

    - by Chris Lee
    Hi all, I am implementing a simulated b/s stock data system. I am using flex and c# for client and server sides. I found flash has a security policy and I handled the policy-file-request in my server code. But seems it doesn't work, because the code jumped out at "socket.Receive(b)" after connection. I've tried sending message on client in the connection handler, in that case the server can receive correct message. But the auto-generated "policy-file-request" can never be received, and the client can get no data sending from server. Here I put my code snippet. my ActionScript code: public class StockClient extends Sprite { private var hostName:String = "192.168.84.103"; private var port:uint = 55555; private var socket:XMLSocket; public function StockClient() { socket = new XMLSocket(); configureListeners(socket); socket.connect(hostName, port); } public function send(data:Object) : void{ socket.send(data); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.CLOSE, closeHandler); dispatcher.addEventListener(Event.CONNECT, connectHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); dispatcher.addEventListener(ProgressEvent.SOCKET_DATA, dataHandler); } private function closeHandler(event:Event):void { trace("closeHandler: " + event); } private function connectHandler(event:Event):void { trace("connectHandler: " + event); //following testing message can be received, but client can't invoke data handler //send("<policy-file-request/>"); } private function dataHandler(event:ProgressEvent):void { //never fired trace("dataHandler: " + event); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); } } my C# code: const int PORT_NUMBER = 55555; const String BEGIN_REQUEST = "begin"; const String END_REQUEST = "end"; const String POLICY_REQUEST = "<policy-file-request/>\u0000"; const String POLICY_FILE = "<?xml version=\"1.0\"?>\n" + "<!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\n" + "<cross-domain-policy> \n" + " <allow-access-from domain=\"*\" to-ports=\"55555\"/> \n" + "</cross-domain-policy>\u0000"; ................ private void startListening() { provider = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); provider.Bind(new IPEndPoint(IPAddress.Parse("192.168.84.103"), PORT_NUMBER)); provider.Listen(10); isListened = true; while (isListened) { Socket socket = provider.Accept(); Console.WriteLine("connect!"); byte[] b = new byte[1024]; int receiveLength = 0; try { // code jump out at this statement receiveLength = socket.Receive(b); } catch (Exception e) { Debug.WriteLine(e.ToString()); } String request = System.Text.Encoding.UTF8.GetString(b, 0, receiveLength); Console.WriteLine("request:"+request); if (request == POLICY_REQUEST) { socket.Send(Encoding.UTF8.GetBytes(POLICY_FILE)); Console.WriteLine("response:" + POLICY_FILE); } else if (request == END_REQUEST) { Dispose(socket); } else { StartSocket(socket); break; } } } Sorry for the long code, please someone help with it, thanks a million

    Read the article

  • Linq to SQL NullReferenceException's: A random needle in a haystack!

    - by Shane
    I'm getting NullReferenceExeceptions at seemly random times in my application and can't track down what could be causing the error. I'll do my best to describe the scenario and setup. Any and all suggestions greatly appreciated! C# .net 3.5 Forms Application, but I use the WebFormRouting library built by Phil Haack (http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx) to leverage the Routing libraries of .net (usually used in conjunction with MVC) - intead of using url rewriting for my urls. My database has 60 tables. All Normalized. It's just a massive application. (SQL server 2008) All queries are built with Linq to SQL in code (no SP's). Each time a new instance of my data context is created. I use only one data context with all relationships defined in 4 relationship diagrams in SQL Server. the data context gets created a lot. I let the closing of the data context be handled automatically. I've heard arguments both sides about whether you should leave to be closed automatically or do it yourself. In this case I do it myself. It doesnt seem to matter if I'm creating a lot of instances of the data context or just one. For example, I've got a vote-up button. with the following code, and it errors probably 1 in 10-20 times. protected void VoteUpLinkButton_Click(object sender, EventArgs e) { DatabaseDataContext db = new DatabaseDataContext(); StoryVote storyVote = new StoryVote(); storyVote.StoryId = storyId; storyVote.UserId = Utility.GetUserId(Context); storyVote.IPAddress = Utility.GetUserIPAddress(); storyVote.CreatedDate = DateTime.Now; storyVote.IsDeleted = false; db.StoryVotes.InsertOnSubmit(storyVote); db.SubmitChanges(); // If this story is not yet published, check to see if we should publish it. Make sure that // it is already approved. if (story.PublishedDate == null && story.ApprovedDate != null) { Utility.MakeUpcommingNewsPopular(storyId); } // Refresh our page. Response.Redirect("/news/" + category.UniqueName + "/" + RouteData.Values["year"].ToString() + "/" + RouteData.Values["month"].ToString() + "/" + RouteData.Values["day"].ToString() + "/" + RouteData.Values["uniquename"].ToString()); } The last thing I tried was the "Auto Close" flag setting on SQL Server. This was set to true and I changed to false. Doesnt seem to have done the trick although has had a good overall effect. Here's a detailed that wasnt caught. I also get slighly different errors when caught by my try/catch's. System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. --- System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Util.StringUtil.GetStringHashCode(String s) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.WebControls.TextBox.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --- at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.forms_news_detail_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) HELP!!!

    Read the article

  • Odd performance with C# Asynchronous server socket

    - by The.Anti.9
    I'm working on a web server in C# and I have it running on Asynchronous socket calls. The weird thing is that for some reason, when you start loading pages, the 3rd request is where the browser won't connect. It just keeps saying "Connecting..." and doesn't ever stop. If I hit stop. and then refresh, it will load again, but if I try another time after that it does the thing where it doesn't load again. And it continues in that cycle. I'm not really sure what is making it do that. The code is kind of hacked together from a couple of examples and some old code I had. Any miscellaneous tips would be helpful as well. Heres my little Listener class that handles everything (pastied here. thought it might be easier to read this way) using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace irek.Server { public class Listener { private int port; private Socket server; private Byte[] data = new Byte[2048]; static ManualResetEvent allDone = new ManualResetEvent(false); public Listener(int _port) { port = _port; } public void Run() { server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, port); server.Bind(iep); Console.WriteLine("Server Initialized."); server.Listen(5); Console.WriteLine("Listening..."); while (true) { allDone.Reset(); server.BeginAccept(new AsyncCallback(AcceptCon), server); allDone.WaitOne(); } } private void AcceptCon(IAsyncResult iar) { allDone.Set(); Socket s = (Socket)iar.AsyncState; Socket s2 = s.EndAccept(iar); SocketStateObject state = new SocketStateObject(); state.workSocket = s2; s2.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), state); } private void Read(IAsyncResult iar) { try { SocketStateObject state = (SocketStateObject)iar.AsyncState; Socket s = state.workSocket; int read = s.EndReceive(iar); if (read > 0) { state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read)); if (s.Available > 0) { s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), state); return; } } if (state.sb.Length > 1) { string requestString = state.sb.ToString(); // HANDLE REQUEST HERE // Temporary response string resp = "<h1>It Works!</h1>"; string head = "HTTP/1.1 200 OK\r\nContent-Type: text/html;\r\nServer: irek\r\nContent-Length:"+resp.Length+"\r\n\r\n"; byte[] answer = Encoding.ASCII.GetBytes(head+resp); // end temp. state.workSocket.BeginSend(answer, 0, answer.Length, SocketFlags.None, new AsyncCallback(Send), state.workSocket); } } catch (Exception) { return; } } private void Send(IAsyncResult iar) { try { SocketStateObject state = (SocketStateObject)iar.AsyncState; int sent = state.workSocket.EndSend(iar); state.workSocket.Shutdown(SocketShutdown.Both); state.workSocket.Close(); } catch (Exception) { } return; } } } And my SocketStateObject: public class SocketStateObject { public Socket workSocket = null; public const int BUFFER_SIZE = 1024; public byte[] buffer = new byte[BUFFER_SIZE]; public StringBuilder sb = new StringBuilder(); }

    Read the article

< Previous Page | 7 8 9 10 11 12  | Next Page >