Search Results

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

Page 4/12 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • C#.NET Socket Programming: Connecting to remote computers.

    - by Gio Borje
    I have a typical server in my end and a friend using a client to connect to my IP/Port and he consistently receives the exception: "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond {MY_IP}:{MY_PORT}"—You don't need to know my IP. The client and server, however, work fine on the loopback address (127.0.0.1). I also do not have any firewall nor is windows firewall active. Server: static void Main(string[] args) { Console.Title = "Socket Server"; Console.WriteLine("Listening for messages..."); Socket serverSock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress serverIP = IPAddress.Any; IPEndPoint serverEP = new IPEndPoint(serverIP, 33367); SocketPermission perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "98.112.235.18", 33367); serverSock.Bind(serverEP); serverSock.Listen(10); while (true) { Socket connection = serverSock.Accept(); Byte[] serverBuffer = new Byte[8]; String message = String.Empty; while (connection.Available > 0) { int bytes = connection.Receive( serverBuffer, serverBuffer.Length, 0); message += Encoding.UTF8.GetString( serverBuffer, 0, bytes); } Console.WriteLine(message); connection.Close(); } } Client: static void Main(string[] args) { // Design the client a bit Console.Title = "Socket Client"; Console.Write("Enter the IP of the server: "); IPAddress clientIP = IPAddress.Parse(Console.ReadLine()); String message = String.Empty; while (true) { Console.Write("Enter the message to send: "); // The messsage to send message = Console.ReadLine(); IPEndPoint clientEP = new IPEndPoint(clientIP, 33367); // Setup the socket Socket clientSock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Attempt to establish a connection to the server Console.Write("Establishing connection to the server... "); try { clientSock.Connect(clientEP); // Send the message clientSock.Send(Encoding.UTF8.GetBytes(message)); clientSock.Shutdown(SocketShutdown.Both); clientSock.Close(); Console.Write("Message sent successfully.\n\n"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }

    Read the article

  • Comparison of IPEndPoint objects not working

    - by Martin Mizzell
    I have an IPEndPoint a and b, whose IPAddress and Port are exactly the same, but the == operator is on the IPEndPoint not returning true. To make things even stranger, I tried to circumvent the problem by simply comparing the IPAddress and Port individually and it is STILL not returning true. Has anyone encountered this before? If so, I am all ears to performant solutions. We have collections of as many as 10k IPEndPoints and are querying into them via LINQ (PLINQ pretty soon).

    Read the article

  • MvcExtensions - PerRequestTask

    - by kazimanzurrashid
    In the previous post, we have seen the BootstrapperTask which executes when the application starts and ends, similarly there are times when we need to execute some custom logic when a request starts and ends. Usually, for this kind of scenario we create HttpModule and hook the begin and end request events. There is nothing wrong with this approach, except HttpModules are not at all IoC containers friendly, also defining the HttpModule execution order is bit cumbersome, you either have to modify the machine.config or clear the HttpModules and add it again in web.config. Instead, you can use the PerRequestTask which is very much container friendly as well as supports execution orders. Lets few examples where it can be used. Remove www Subdomain Lets say we want to remove the www subdomain, so that if anybody types http://www.mydomain.com it will automatically redirects to http://mydomain.com. public class RemoveWwwSubdomain : PerRequestTask { public RemoveWww() { Order = DefaultOrder - 1; } protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext) { const string Prefix = "http://www."; Check.Argument.IsNotNull(executionContext, "executionContext"); HttpContextBase httpContext = executionContext.HttpContext; string url = httpContext.Request.Url.ToString(); bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); bool shouldContinue = true; if (startsWith3W) { string newUrl = "http://" + url.Substring(Prefix.Length); HttpResponseBase response = httpContext.Response; response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.Status = "301 Moved Permanently"; response.RedirectLocation = newUrl; response.SuppressContent = true; shouldContinue = false; } return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break; } } As you can see, first, we are setting the order so that we do not have to execute the remaining tasks of the chain when we are redirecting, next in the ExecuteCore, we checking the whether www is present, if present we are sending a permanently moved http status code and breaking the task execution chain otherwise we are continuing with the chain. Blocking IP Address Lets take another scenario, your application is hosted in a shared hosting environment where you do not have the permission to change the IIS setting and you want to block certain IP addresses from visiting your application. Lets say, you maintain a list of IP address in database/xml files which you want to block, you have a IBannedIPAddressRepository service which is used to match banned IP Address. public class BlockRestrictedIPAddress : PerRequestTask { protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext) { bool shouldContinue = true; HttpContextBase httpContext = executionContext.HttpContext; if (!httpContext.Request.IsLocal) { string ipAddress = httpContext.Request.UserHostAddress; HttpResponseBase httpResponse = httpContext.Response; if (executionContext.ServiceLocator.GetInstance<IBannedIPAddressRepository>().IsMatching(ipAddress)) { httpResponse.StatusCode = (int)HttpStatusCode.Forbidden; httpResponse.StatusDescription = "IPAddress blocked."; shouldContinue = false; } } return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break; } } Managing Database Session Now, let see how it can be used to manage NHibernate session, assuming that ISessionFactory of NHibernate is already registered in our container. public class ManageNHibernateSession : PerRequestTask { private ISession session; protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext) { ISessionFactory factory = executionContext.ServiceLocator.GetInstance<ISessionFactory>(); session = factory.OpenSession(); return TaskContinuation.Continue; } protected override void DisposeCore() { session.Close(); session.Dispose(); } } As you can see PerRequestTask can be used to execute small and precise tasks in the begin/end request, certainly if you want to execute other than begin/end request there is no other alternate of HttpModule. That’s it for today, in the next post, we will discuss about the Action Filters, so stay tuned.

    Read the article

  • android client not working [migrated]

    - by Syeda Zunairah
    i have a java client and c# server the server code is static Socket listeningSocket; static Socket socket; static Thread thrReadRequest; static int iPort = 4444; static int iConnectionQueue = 100; static void Main(string[] args) { Console.WriteLine(IPAddress.Parse(getLocalIPAddress()).ToString()); try { listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //listeningSocket.Bind(new IPEndPoint(0, iPort)); listeningSocket.Bind(new IPEndPoint(IPAddress.Parse(getLocalIPAddress()), iPort)); listeningSocket.Listen(iConnectionQueue); thrReadRequest = new Thread(new ThreadStart(getRequest)); thrReadRequest.Start(); } catch (Exception e) { Console.WriteLine("Winsock error: " + e.ToString()); //throw; } } static private void getRequest() { int i = 0; while (true) { i++; Console.WriteLine("Outside Try i = {0}", i.ToString()); try { socket = listeningSocket.Accept(); // Receiving //byte[] rcvLenBytes = new byte[4]; //socket.Receive(rcvLenBytes); //int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0); //byte[] rcvBytes = new byte[rcvLen]; //socket.Receive(rcvBytes); //String formattedBuffer = System.Text.Encoding.ASCII.GetString(rcvBytes); byte[] buffer = new byte[socket.SendBufferSize]; int iBufferLength = socket.Receive(buffer, 0, buffer.Length, 0); Console.WriteLine("Received {0}", iBufferLength); Array.Resize(ref buffer, iBufferLength); string formattedBuffer = Encoding.ASCII.GetString(buffer); Console.WriteLine("Data received by Client: {0}", formattedBuffer); if (formattedBuffer == "quit") { socket.Close(); listeningSocket.Close(); Environment.Exit(0); } Console.WriteLine("Inside Try i = {0}", i.ToString()); Thread.Sleep(500); } catch (Exception e) { //socket.Close(); Console.WriteLine("Receiving error: " + e.ToString()); Console.ReadKey(); //throw; } finally { socket.Close(); //listeningsocket.close(); } } } static private string getLocalIPAddress() { IPHostEntry host; string localIP = ""; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } return localIP; } } and the jave android code is private TCPClient mTcpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = (EditText) findViewById(R.id.edit_message); Button send = (Button)findViewById(R.id.sendbutton); // connect to the server new connectTask().execute(""); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String message = editText.getText().toString(); //sends the message to the server if (mTcpClient != null) { mTcpClient.sendMessage(message); } editText.setText(""); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public class connectTask extends AsyncTask<String,String,TCPClient> { @Override protected TCPClient doInBackground(String... message) { mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() { @Override public void messageReceived(String message) { publishProgress(message); } }); mTcpClient.run(); return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); } } } when i run the server it gives output of try i=1. can any one tell me what to do next

    Read the article

  • Cleaning up PHP Code

    - by Michael
    Hi, I've noticed I am a very sloppy coder and do things out of the ordinary. Can you take a look at my code and give me some tips on how to code more efficiently? What can I do to improve? session_start(); /check if the token is correct/ if ($_SESSION['token'] == $_GET['custom1']){ /*connect to db*/ mysql_connect('localhost','x','x') or die(mysql_error()); mysql_select_db('x'); /*get data*/ $orderid = mysql_real_escape_string($_GET['order_id']); $amount = mysql_real_escape_string($_GET['amount']); $product = mysql_real_escape_string($_GET['product1Name']); $cc = mysql_real_escape_string($_GET['Credit_Card_Number']); $length = strlen($cc); $last = 4; $start = $length - $last; $last4 = substr($cc, $start, $last); $ipaddress = mysql_real_escape_string($_GET['ipAddress']); $accountid = $_SESSION['user_id']; $credits = mysql_real_escape_string($_GET['custom3']); /*insert history into db*/ mysql_query("INSERT into billinghistory (orderid, price, description, credits, last4, orderip, accountid) VALUES ('$orderid', '$amount', '$product', '$credits', '$last4', '$ipaddress', '$accountid')"); /*add the credits to the users account*/ mysql_query("UPDATE accounts SET credits = credits + $credits WHERE user_id = '$accountid'"); /*redirect is successful*/ header("location: index.php?x=1"); }else{ /*something messed up*/ header("location: error.php"); }

    Read the article

  • Avoid using InetAddress - Getting a raw IP address in network byte order

    - by Mylo
    Hey, I am trying to use the MaxMind GeoLite Country database on the Google App Engine. However, I am having difficulty getting the Java API to work as it relies on the InetAddress class which is not available to use on the App Engine. However, I am not sure if there is a simple workaround as it appears it only uses the InetAddress class to determine the IP of a given hostname. In my case, the hostname is always an IP anyway. What I need is a way to convert an IP address represented as a String into a byte array of network byte order (which the addr.getAddress() method of the InetAddress class provides). This is the code the current API uses, I need to find a way of removing all references to InetAddress whilst ensuring it still works! Thanks for your time. /** * Returns the country the IP address is in. * * @param ipAddress String version of an IP address, i.e. "127.0.0.1" * @return the country the IP address is from. */ public Country getCountry(String ipAddress) { InetAddress addr; try { addr = InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { return UNKNOWN_COUNTRY; } return getCountry(bytesToLong(addr.getAddress())); }

    Read the article

  • using RHEL5 as a router

    - by gopikrishna7779
    Dear Sir, I am planning to use a RHEL5 installed computer as a internet connection sharing device. I mean I want to share the internet connection through it I have installed 2 Lan cards in it eth0 and eth1 eth0 Internet eth1 LAN eth0 configuration as follows ; Ipaddress : 115.252.64.187 Subnet : 255.255.255.240 Gateway : 115.252.64.177 I wrote the following entries in Vim /etc/resolv.conf nameserver 202.138.96.2 (preferred DNS Server) nameserver 202.138.103.2 (secondary DNS server) :q! then eth1 ipaddress : 192.168.1.1 subnet : 255.255.255.0 gateway : 192.168.1.1 (I am confused which gateway I need to use in the above scenario) I am unable to ping to my lan and I am able to connect to the Internet. Please let me know the sollution for this. Thanks in advance. regards, G.Gopi Krishna

    Read the article

  • Glusterfs : 'No route to host' for fstab mount in CentOS

    - by son_of_fire
    I am using glusterfs, and am using fstab in this way: <IPADDRESS>:/<VOLUMENAME> /some/mount/point glusterfs defaults,_netdev 0 0 but the logs for the mount continue to say the following. [<TIMESTAMP>] E [socket.c:2161:socket_connect_finish] 0-<VOLUMENAME>-client-1: connection to <IPADDRESS>:24007 failed (No route to host) I know this is not true, since when the system is up and running, I can easily issue a mount and the volume gets mounted. (I've done this by using rc.local) after reading more I have seen that using _netdev is preferred, and that if the host cannot be reached netfs will remount the volume after the network comes up, but that is not happening. (netfs is running). Is there a way to make the mount happen at a different time without using a script? (I would prefer to use fstab to manage the mounting even though I can use a script.)

    Read the article

  • internal DNS server limiting the speed as 55kb/sec ?

    - by kartook
    Hi all , Thanks in advance to everyone . Here is my Question . 1 .We have LAN internal DNS server ( 192.168.205.200 ) 2. DNS server Running on my ADDITIONAL DOMAIN CONTROLLER 3. Tested with Nslookup IPADDRESS and hostname resolving without any error . 4 .DHCP server Running on 3750 Switch ( Checked with CISCO Confirmed the configuration ) .DNS name server pointed to 192.168.205.200 . ISSUE : 1.Host getting ipaddress and DNS from DHCP server .Maximum file transfer Bandwidth 55KB/sec . 2. Assigned Static DNS on Host as ISP DNSServer Address, host getting full bandwidth whihc is 1mb/sec Thanks Kartook

    Read the article

  • MySQL Workbench sends computer name with login not IP

    - by Android Addict
    I am attempting to connect MySQLWorkbench to a remote MySQL Server. The server has granted access to user@IPAddress However, when I try to connect MySQLWorkbench, it sends user@computername instead. How do I configure the connection to use the IP address instead in MySQLWorkbench? Reference: The remote server is on the local network, so I need to use the local IP address assigned to my client. EDIT What I have tried so far: from the server: mysql -u user@IPAddress -p --host=(ServerIPAddress) Returns: mysql> So that tells me the user account is operational. Furthermore, I confirmed it exists using: select user from mysql.user; returning a table of all users, of which the user I am using is present. I have also opened the port 3306: sbin/iptables -A INPUT -i eth0 -s clientIPAddress -p tcp --destination-port3306 -j ACCEPT Still I encounter Access Denied

    Read the article

  • Terminal command to send data (plain text string) to a port at a remote computer.

    - by Eddy
    I am trying to send data (plain text string) to a port at a remote computer using terminal utility. The string would be used to trigger something on the remote computer running a program that would listen to that specific port. I used netcat command and tried a few combination of the following but can't seem to get the parameter right. Can someone point me out where am I doing wrong? eddy-2:Desktop eddy$ nc IPADDRESS PORT woc.txt eddy-2:Desktop eddy$ nc IPADDRESS PORT < woc.txt P.S: woc.txt contains plain text string of the said command. Edit: I am trying to send a string from OSX to Windows XP where the specific port is open by default.

    Read the article

  • phpmyadmin forbidden after changing config for my IP

    - by Jonathan Kushner
    I followed the phpmyadmin setup and changed the config to require ip my ipaddress and allow from my ipaddress and its still telling me forbidden You don't have permission to access /phpmyadmin on this server. when I try to access the page on my browser (my server is not located on my machine). I installed everything using root. I also chmod 775 the entire phpMyAdmin folder. Im running RHEL 6.1. Any idea what to do at this point? Here is my /etc/httpd/conf.d/phpMyAdmin.conf: <Directory /usr/share/phpMyAdmin/> <IfModule mod_authz_core.c> # Apache 2.4 <RequireAny> Require ip myserveripaddress Require ip ::1 </RequireAny> </IfModule> <IfModule !mod_authz_core.c> # Apache 2.2 Order Deny,Allow Deny from All Allow from myserveripaddress Allow from ::1 </IfModule> </Directory>

    Read the article

  • How to get the IP Address for your Local Area Connection on Windows Server?

    - by Geo
    I want to create a batch or vbs file that will put together a url and executed. Part of that url needs to be the actual ip address of the machine. How I am able to get that IP address in a variable to include it on the script? EDIT 1: I found out that the command below will give me the IP Address, but still don't know how to get that value into a variable to use it in a script. c:\> wmic NICCONFIG WHERE IPEnabled=true GET IPAddress /format:csv Node,IPAddress IP-0AFB,{10.25.5.2}

    Read the article

  • Why does async BeginReceiveFrom never time out on a raw socket?

    - by James Hugard
    Writing an asynchronous Ping using Raw Sockets in F#, to enable parallel requests using as few threads as possible. Not using "System.Net.NetworkInformation.Ping", because it appears to allocate one thread per request. Am also interested in using F# async workflows. The synchronous version below correctly times out when the target host does not exist/respond, but the asynchronous version hangs. Both work when the host does respond. Not sure if this is a .NET issue, or an F# one... Any ideas? (note: the process must run as Admin to allow Raw Socket access) This throws a timeout: let result = Ping.Ping ( IPAddress.Parse( "192.168.33.22" ), 1000 ) However, this hangs: let result = Ping.AsyncPing ( IPAddress.Parse( "192.168.33.22" ), 1000 ) |> Async.RunSynchronously Here's the code... module Ping open System open System.Net open System.Net.Sockets open System.Threading //---- ICMP Packet Classes type IcmpMessage (t : byte) = let mutable m_type = t let mutable m_code = 0uy let mutable m_checksum = 0us member this.Type with get() = m_type member this.Code with get() = m_code member this.Checksum = m_checksum abstract Bytes : byte array default this.Bytes with get() = [| m_type m_code byte(m_checksum) byte(m_checksum >>> 8) |] member this.GetChecksum() = let mutable sum = 0ul let bytes = this.Bytes let mutable i = 0 // Sum up uint16s while i < bytes.Length - 1 do sum <- sum + uint32(BitConverter.ToUInt16( bytes, i )) i <- i + 2 // Add in last byte, if an odd size buffer if i <> bytes.Length then sum <- sum + uint32(bytes.[i]) // Shuffle the bits sum <- (sum >>> 16) + (sum &&& 0xFFFFul) sum <- sum + (sum >>> 16) sum <- ~~~sum uint16(sum) member this.UpdateChecksum() = m_checksum <- this.GetChecksum() type InformationMessage (t : byte) = inherit IcmpMessage(t) let mutable m_identifier = 0us let mutable m_sequenceNumber = 0us member this.Identifier = m_identifier member this.SequenceNumber = m_sequenceNumber override this.Bytes with get() = Array.append (base.Bytes) [| byte(m_identifier) byte(m_identifier >>> 8) byte(m_sequenceNumber) byte(m_sequenceNumber >>> 8) |] type EchoMessage() = inherit InformationMessage( 8uy ) let mutable m_data = Array.create 32 32uy do base.UpdateChecksum() member this.Data with get() = m_data and set(d) = m_data <- d this.UpdateChecksum() override this.Bytes with get() = Array.append (base.Bytes) (this.Data) //---- Synchronous Ping let Ping (host : IPAddress, timeout : int ) = let mutable ep = new IPEndPoint( host, 0 ) let socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let mutable buffer = packet.Bytes try if socket.SendTo( buffer, ep ) <= 0 then raise (SocketException()) buffer <- Array.create (buffer.Length + 20) 0uy let mutable epr = ep :> EndPoint if socket.ReceiveFrom( buffer, &epr ) <= 0 then raise (SocketException()) finally socket.Close() buffer //---- Entensions to the F# Async class to allow up to 5 paramters (not just 3) type Async with static member FromBeginEnd(arg1,arg2,arg3,arg4,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,iar,state)), endAction, ?cancelAction=cancelAction) static member FromBeginEnd(arg1,arg2,arg3,arg4,arg5,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,arg5,iar,state)), endAction, ?cancelAction=cancelAction) //---- Extensions to the Socket class to provide async SendTo and ReceiveFrom type System.Net.Sockets.Socket with member this.AsyncSendTo( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginSendTo, this.EndSendTo ) member this.AsyncReceiveFrom( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginReceiveFrom, (fun asyncResult -> this.EndReceiveFrom(asyncResult, remoteEP) ) ) //---- Asynchronous Ping let AsyncPing (host : IPAddress, timeout : int ) = async { let ep = IPEndPoint( host, 0 ) use socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let outbuffer = packet.Bytes try let! result = socket.AsyncSendTo( outbuffer, 0, outbuffer.Length, SocketFlags.None, ep ) if result <= 0 then raise (SocketException()) let epr = ref (ep :> EndPoint) let inbuffer = Array.create (outbuffer.Length + 256) 0uy let! result = socket.AsyncReceiveFrom( inbuffer, 0, inbuffer.Length, SocketFlags.None, epr ) if result <= 0 then raise (SocketException()) return inbuffer finally socket.Close() }

    Read the article

  • How to detect a timeout when using asynchronous Socket.BeginReceive?

    - by James Hugard
    Writing an asynchronous Ping using Raw Sockets in F#, to enable parallel requests using as few threads as possible. Not using "System.Net.NetworkInformation.Ping", because it appears to allocate one thread per request. Am also interested in using F# async workflows. The synchronous version below correctly times out when the target host does not exist/respond, but the asynchronous version hangs. Both work when the host does respond. Not sure if this is a .NET issue, or an F# one... Any ideas? (note: the process must run as Admin to allow Raw Socket access) This throws a timeout: let result = Ping.Ping ( IPAddress.Parse( "192.168.33.22" ), 1000 ) However, this hangs: let result = Ping.AsyncPing ( IPAddress.Parse( "192.168.33.22" ), 1000 ) |> Async.RunSynchronously Here's the code... module Ping open System open System.Net open System.Net.Sockets open System.Threading //---- ICMP Packet Classes type IcmpMessage (t : byte) = let mutable m_type = t let mutable m_code = 0uy let mutable m_checksum = 0us member this.Type with get() = m_type member this.Code with get() = m_code member this.Checksum = m_checksum abstract Bytes : byte array default this.Bytes with get() = [| m_type m_code byte(m_checksum) byte(m_checksum >>> 8) |] member this.GetChecksum() = let mutable sum = 0ul let bytes = this.Bytes let mutable i = 0 // Sum up uint16s while i < bytes.Length - 1 do sum <- sum + uint32(BitConverter.ToUInt16( bytes, i )) i <- i + 2 // Add in last byte, if an odd size buffer if i <> bytes.Length then sum <- sum + uint32(bytes.[i]) // Shuffle the bits sum <- (sum >>> 16) + (sum &&& 0xFFFFul) sum <- sum + (sum >>> 16) sum <- ~~~sum uint16(sum) member this.UpdateChecksum() = m_checksum <- this.GetChecksum() type InformationMessage (t : byte) = inherit IcmpMessage(t) let mutable m_identifier = 0us let mutable m_sequenceNumber = 0us member this.Identifier = m_identifier member this.SequenceNumber = m_sequenceNumber override this.Bytes with get() = Array.append (base.Bytes) [| byte(m_identifier) byte(m_identifier >>> 8) byte(m_sequenceNumber) byte(m_sequenceNumber >>> 8) |] type EchoMessage() = inherit InformationMessage( 8uy ) let mutable m_data = Array.create 32 32uy do base.UpdateChecksum() member this.Data with get() = m_data and set(d) = m_data <- d this.UpdateChecksum() override this.Bytes with get() = Array.append (base.Bytes) (this.Data) //---- Synchronous Ping let Ping (host : IPAddress, timeout : int ) = let mutable ep = new IPEndPoint( host, 0 ) let socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let mutable buffer = packet.Bytes try if socket.SendTo( buffer, ep ) <= 0 then raise (SocketException()) buffer <- Array.create (buffer.Length + 20) 0uy let mutable epr = ep :> EndPoint if socket.ReceiveFrom( buffer, &epr ) <= 0 then raise (SocketException()) finally socket.Close() buffer //---- Entensions to the F# Async class to allow up to 5 paramters (not just 3) type Async with static member FromBeginEnd(arg1,arg2,arg3,arg4,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,iar,state)), endAction, ?cancelAction=cancelAction) static member FromBeginEnd(arg1,arg2,arg3,arg4,arg5,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,arg5,iar,state)), endAction, ?cancelAction=cancelAction) //---- Extensions to the Socket class to provide async SendTo and ReceiveFrom type System.Net.Sockets.Socket with member this.AsyncSendTo( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginSendTo, this.EndSendTo ) member this.AsyncReceiveFrom( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginReceiveFrom, (fun asyncResult -> this.EndReceiveFrom(asyncResult, remoteEP) ) ) //---- Asynchronous Ping let AsyncPing (host : IPAddress, timeout : int ) = async { let ep = IPEndPoint( host, 0 ) use socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let outbuffer = packet.Bytes try let! result = socket.AsyncSendTo( outbuffer, 0, outbuffer.Length, SocketFlags.None, ep ) if result <= 0 then raise (SocketException()) let epr = ref (ep :> EndPoint) let inbuffer = Array.create (outbuffer.Length + 256) 0uy let! result = socket.AsyncReceiveFrom( inbuffer, 0, inbuffer.Length, SocketFlags.None, epr ) if result <= 0 then raise (SocketException()) return inbuffer finally socket.Close() }

    Read the article

  • Jumbled byte array after using TcpClient and TcpListener

    - by Dylan
    I want to use the TcpClient and TcpListener to send an mp3 file over a network. I implemented a solution of this using sockets, but there were some issues so I am investigating a new/better way to send a file. I create a byte array which looks like this: length_of_filename|filename|file This should then be transmitted using the above mentioned classes, yet on the server side the byte array I read is completely messed up and I'm not sure why. The method I use to send: public static void Send(String filePath) { try { IPEndPoint endPoint = new IPEndPoint(Settings.IpAddress, Settings.Port + 1); Byte[] fileData = File.ReadAllBytes(filePath); FileInfo fi = new FileInfo(filePath); List<byte> dataToSend = new List<byte>(); dataToSend.AddRange(BitConverter.GetBytes(Encoding.Unicode.GetByteCount(fi.Name))); // length of filename dataToSend.AddRange(Encoding.Unicode.GetBytes(fi.Name)); // filename dataToSend.AddRange(fileData); // file binary data using (TcpClient client = new TcpClient()) { client.Connect(Settings.IpAddress, Settings.Port + 1); // Get a client stream for reading and writing. using (NetworkStream stream = client.GetStream()) { // server is ready stream.Write(dataToSend.ToArray(), 0, dataToSend.ToArray().Length); } } } catch (ArgumentNullException e) { Debug.WriteLine(e); } catch (SocketException e) { Debug.WriteLine(e); } } } Then on the server side it looks as follows: private void Listen() { TcpListener server = null; try { // Setup the TcpListener Int32 port = Settings.Port + 1; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[1024]; List<byte> data; // Enter the listening loop. while (true) { Debug.WriteLine("Waiting for a connection... "); string filePath = string.Empty; // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. using (TcpClient client = server.AcceptTcpClient()) { Debug.WriteLine("Connected to client!"); data = new List<byte>(); // Get a stream object for reading and writing using (NetworkStream stream = client.GetStream()) { // Loop to receive all the data sent by the client. while ((stream.Read(bytes, 0, bytes.Length)) != 0) { data.AddRange(bytes); } } } int fileNameLength = BitConverter.ToInt32(data.ToArray(), 0); filePath = Encoding.Unicode.GetString(data.ToArray(), 4, fileNameLength); var binary = data.GetRange(4 + fileNameLength, data.Count - 4 - fileNameLength); Debug.WriteLine("File successfully downloaded!"); // write it to disk using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Append))) { writer.Write(binary.ToArray(), 0, binary.Count); } } } catch (Exception ex) { Debug.WriteLine(ex); } finally { // Stop listening for new clients. server.Stop(); } } Can anyone see something that I am missing/doing wrong?

    Read the article

  • Why does BeginReceiveFrom never time out?

    - by James Hugard
    I am writing an asynchronous Ping using Raw Sockets in F#, to enable parallel requests using as few threads as possible ("System.Net.NetworkInformation.Ping" appears to use one thread per request, but have not tested this... also am interested in using F# async workflows). The synchronous version below correctly times out when the target host does not exist/respond, but the asynchronous version hangs. Both work when the host does respond... Any ideas? (note: the process must run as Admin for this code to work) This throws a timeout: let result = Ping.Ping ( IPAddress.Parse( "192.168.33.22" ), 1000 ) However, this hangs: let result = Ping.PingAsync ( IPAddress.Parse( "192.168.33.22" ), 1000 ) |> Async.RunSynchronously Here's the code... module Ping open System open System.Net open System.Net.Sockets open System.Threading //---- ICMP Packet Classes type IcmpMessage (t : byte) = let mutable m_type = t let mutable m_code = 0uy let mutable m_checksum = 0us member this.Type with get() = m_type member this.Code with get() = m_code member this.Checksum = m_checksum abstract Bytes : byte array default this.Bytes with get() = [| m_type m_code byte(m_checksum) byte(m_checksum >>> 8) |] member this.GetChecksum() = let mutable sum = 0ul let bytes = this.Bytes let mutable i = 0 // Sum up uint16s while i < bytes.Length - 1 do sum <- sum + uint32(BitConverter.ToUInt16( bytes, i )) i <- i + 2 // Add in last byte, if an odd size buffer if i <> bytes.Length then sum <- sum + uint32(bytes.[i]) // Shuffle the bits sum <- (sum >>> 16) + (sum &&& 0xFFFFul) sum <- sum + (sum >>> 16) sum <- ~~~sum uint16(sum) member this.UpdateChecksum() = m_checksum <- this.GetChecksum() type InformationMessage (t : byte) = inherit IcmpMessage(t) let mutable m_identifier = 0us let mutable m_sequenceNumber = 0us member this.Identifier = m_identifier member this.SequenceNumber = m_sequenceNumber override this.Bytes with get() = Array.append (base.Bytes) [| byte(m_identifier) byte(m_identifier >>> 8) byte(m_sequenceNumber) byte(m_sequenceNumber >>> 8) |] type EchoMessage() = inherit InformationMessage( 8uy ) let mutable m_data = Array.create 32 32uy do base.UpdateChecksum() member this.Data with get() = m_data and set(d) = m_data <- d this.UpdateChecksum() override this.Bytes with get() = Array.append (base.Bytes) (this.Data) //---- Synchronous Ping let Ping (host : IPAddress, timeout : int ) = let mutable ep = new IPEndPoint( host, 0 ) let socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let mutable buffer = packet.Bytes try if socket.SendTo( buffer, ep ) <= 0 then raise (SocketException()) buffer <- Array.create (buffer.Length + 20) 0uy let mutable epr = ep :> EndPoint if socket.ReceiveFrom( buffer, &epr ) <= 0 then raise (SocketException()) finally socket.Close() buffer //---- Entensions to the F# Async class to allow up to 5 paramters (not just 3) type Async with static member FromBeginEnd(arg1,arg2,arg3,arg4,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,iar,state)), endAction, ?cancelAction=cancelAction) static member FromBeginEnd(arg1,arg2,arg3,arg4,arg5,beginAction,endAction,?cancelAction): Async<'T> = Async.FromBeginEnd((fun (iar,state) -> beginAction(arg1,arg2,arg3,arg4,arg5,iar,state)), endAction, ?cancelAction=cancelAction) //---- Extensions to the Socket class to provide async SendTo and ReceiveFrom type System.Net.Sockets.Socket with member this.AsyncSendTo( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginSendTo, this.EndSendTo ) member this.AsyncReceiveFrom( buffer, offset, size, socketFlags, remoteEP ) = Async.FromBeginEnd( buffer, offset, size, socketFlags, remoteEP, this.BeginReceiveFrom, (fun asyncResult -> this.EndReceiveFrom(asyncResult, remoteEP) ) ) //---- Asynchronous Ping let PingAsync (host : IPAddress, timeout : int ) = async { let ep = IPEndPoint( host, 0 ) use socket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout ) socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout ) let packet = EchoMessage() let outbuffer = packet.Bytes try let! result = socket.AsyncSendTo( outbuffer, 0, outbuffer.Length, SocketFlags.None, ep ) if result <= 0 then raise (SocketException()) let epr = ref (ep :> EndPoint) let inbuffer = Array.create (outbuffer.Length + 256) 0uy let! result = socket.AsyncReceiveFrom( inbuffer, 0, inbuffer.Length, SocketFlags.None, epr ) if result <= 0 then raise (SocketException()) return inbuffer finally socket.Close() }

    Read the article

  • How to config socket connect timeout in C#

    - by ninikin
    (C# )When the Client tries to connect to a disconnected IP address, there is a long timeout over 15 seconds... How can we reduce this timeout? What is the method to config it? The code I'm using to set up a socket connection is as following: try { m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(serverIp); int iPortNo = System.Convert.ToInt16(serverPort); IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo); m_clientSocket.Connect(ipEnd); if (m_clientSocket.Connected) { lb_connectStatus.Text = "Connection Established"; WaitForServerData(); } else { } } catch (SocketException se) { lb_connectStatus.Text = "Connection Failed"; MessageBox.Show(se.Message); }

    Read the article

  • How to reuse socket in .NET?

    - by Hermann
    I am trying to reconnect to a socket that I have disconnected from but it won't allow it for some reason even though I called the Disconnect method with the argument "reuseSocket" set to true. _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(ipAddress, port); //...receive data _socket.Disconnect(true); //reuseSocket = true //...wait _socket.Connect(ipAddress, port); //throws an InvalidOperationException: Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed. What am I doing wrong?

    Read the article

  • Dns.GetHostEntry returns multiple IP addresses

    - by spender
    This question probably highlights a lack of understanding of networking principals on my part, rather than a programming issue. I'm doing a lookup on a hostname using Dns.GetHostEntry This returns an IPHostEntry to me, which has an AddressList property which is an array of IPAddress. I always thought there is a 1 to 1 mapping between hostname and IP, but I'm finding that in some cases I get back several IPAddress(es) for the same host. This is a surprise to me. Which part of domain name resolution do I not understand?

    Read the article

  • Specify IP address of WCF endpoint at runtime

    - by Mikey Cee
    I have a bunch of remote machines all running the same WCF service over HTTP. I have a central configuration utility that needs to decide at runtime which of these to connect to. I do not want to define all the endpoints in the configuration file because this is all database driven. I naively tried this: CustomerServiceClient GetClientForIPAddress(string ipAddress) { string address = String.Format("http://{0}/customerservice.svc", ipAddress); var client = new CustomerServiceClient("?", address); return client; } where CustomerServiceClient is my service reference proxy class, but (unsurprisingly) it gave me the following error: Could not find endpoint element with name '?' and contract 'SkyWalkerCustomerService.ICustomerService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element. So how do I declare an endpoint at runtime and point my service reference to it? .NET 3.5

    Read the article

  • UDP Socket Client in .NET

    - by Betamoo
    I use UDP Sokckts in my client application. Here are some code snippets: SendIP = new IPEndPoint(IPAddress.Parse(IP), port); ReceiveIP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0)); socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(ReceiveIP); And to Receive (while(true)): byte[] data = new byte[BUFFERSIZE]; int receivedDataLength = socket.ReceiveFrom(data, ref ReceiveIP); string s= Encoding.ASCII.GetString(data, 0, receivedDataLength); I am doing an infinite while on the receive, there are other things to be done in the while, even if nothing is received.. I want to check if there are actually available data then receive else do not wait.. (Note the current receive method waits until the server sends a message)

    Read the article

  • Socket Communication in C#- IP-Port

    - by Ahmet Altun
    I am testing my socket programs at home, in local network. Server and client programs are running on seperate machines. Server program socket is binded as: serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8999)); Client program (on the other computer) is connected as: clientSocket.Connect(IPAddress.Parse("192.168.2.3"), 8999); Why can Client not communicate with server? Do I need to make some firewall configuration or something like that? Or am I writing Server Ip incorrectly to the Client? (I got it from cmd-ipconfig of server)

    Read the article

  • C++/CLI .ToString() returning error

    - by George Johnston
    I am a beginner to C++/CLI as I come from a C# background. I am currently writing a wrapper for some native C++ code. I have the following methods: void AddToBlockList(System::String^ address) { char* cAddress = (char*)(void*)Marshal::StringToHGlobalAnsi(address); _packetFilter->AddToBlockList(cAddress); } void AddToBlockList(IPAddress^ address) { char* cAddress = (char*)(void*)Marshal::StringToHGlobalAnsi(address.ToString()); _packetFilter->AddToBlockList(cAddress); } ...The first method works fine and converts my string into the character array. However, the second function with the IPAddress object as the signiture gives me the following error: error C2228: left of '.ToString' must have class/struct/union ...When I type ? address.ToString() ...in the command window, the IP Address prints. Not sure where I'm going wrong. Any ideas?

    Read the article

  • SOCKET chat C# with private messaging

    - by Sergei
    I want to create SOCKET chat(server + clients) with private messaging. When client write smth to stream, he should notify server that it is private message for user X, how can i do this? Actually i can do smth like this: string command = "PRIV|" + txtMessage.Text; swSender.WriteLine(command); but i think it isn't good, for example if user wants send message like our "PRIV|" flag it will be errors public class TestChat { private StreamWriter swSender; private IPAddress ipAddr; private void InitializeandSend() { //ip from text box ipAddr = IPAddress.Parse(txtIp.Text); // Start a new TCP connections to the chat server tcpServer = new TcpClient(); tcpServer.Connect(ipAddr, 1986); //... //sending message from text box swSender.WriteLine(txtMessage.Text); swSender.Flush(); } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >