http://searchnetworking.techtarget.com/definition/time-to-live
From this article, im Confused about the defanition about this subject.
is there any chance someone help me undestand better whats going on?
stav.
----------------------------------
EDIT:
i tried to send massage to my self from the same computer.
when i set the TTL value to 0, the pack i send still get to me. why is that?
here is the code:
btw,this line in the Send Method.
server.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, 0);
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class MAIN
{
public static MulticastOption MulticastOption;
private static MulticastOption CreateGroup()
{
MulticastOption = new MulticastOption(IPAddress.Parse("224.100.0.1"));
return MulticastOption;
}
private static void Receive()
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
EndPoint ep = (EndPoint)iep;
sock.Bind(iep);
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, MulticastOption);
//
byte[] data = new byte[1024];
new Thread(new ThreadStart(Send)).Start();
int recv = sock.ReceiveFrom(data, ref ep);
String stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
sock.Close();
}
private static void Send()
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
server.Bind(iep);
server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1")));
server.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, 0);
server.SendTo(Encoding.ASCII.GetBytes("This is a test message"), iep2);
server.Close();
}
public static void Main(String[] args)
{
CreateGroup();
Receive();
Console.ReadKey();
}
}
Client machines set the TTL value when a packet is generated, to indicate the maximum number of hops the packet is permitted to go through.
Each time a packet passes through a router the router will decrement the TTL value.
If the TTL value reaches zero, the router will drop the packet and return an ICMP "hop count exceeded" error message.
The main benefit of the TTL field is to stop packets bouncing around forever in the event of a routing loop, i.e. a network fault that causes packets to bounce around and around between the same set of routers.
Related
I want to send a message from server to an IP/Port but it's not working when I write the channel. I'm not sure what I'm doing wrong.
private Channel channel;
private void createConnection() {
ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
this.bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new SimpleChannelHandler());
}
});
bootstrap.setOption("localAddress", new InetSocketAddress("localhost", 0));
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("child.sendBufferSize", 65536);
bootstrap.setOption("child.receiveBufferSize", 65536);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
this.channel = bootstrap.bind();
}
I'm writing a component using apache camel. When my component proccess, I want it sends a message to an IP/Port.
public void send(Exchange exchange) {
String ip = exchange.getIn().getHeader("ip", String.class);
int port = exchange.getIn().getHeader("port", Integer.class);
Object msg = exchange.getIn().getBody();
InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);
this.channel.write(msg, inetSocketAddress);
}
I'm getting a "getUnsupportedOperationFuture". I'm not sure what I'm doing wrong. I'm using Netty 3.8 and I think the connection is set correctly. Any help?
We use the Windows IoT to connect to another application in network with TCPClient. All works now, except one point which confuse us. When we unplug the network cable from our raspberry Pi (I guess version 2) the Startup application with a GUI is immediately stopped. When we plug in the cable back, after a little time the Startup app is started again.
We use VS2017 to build arm UWP app.
Any idea how to prevent stop of application?
As without your source code,I am not sure what cause your problem.I have tested following pieces codes in raspberry Pi 3, when i unplug the network cable, the application with UI does not stop.In foreground task,asynchronous method is recommend, please reference Asynchronous programming.
Server:
TcpListener tcpListener = new TcpListener(IPAddress.Any, 6550);
tcpListener.Start();
byte[] buffer = new byte[1024];
String data = string.Empty;
while (true)
{
var client = await tcpListener.AcceptTcpClientAsync();
var stream = client.GetStream();
int i = 0;
// Loop to receive all the data sent by the client.
do
{
i = await stream.ReadAsync(buffer, 0, buffer.Length);
if(i > 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(buffer, 0, i);
//Display received message
txtRServerContent.Text = data;
}
} while (i > 0);
}
Client:
TcpClient tcpClient = new TcpClient(AddressFamily.InterNetwork);
await tcpClient.ConnectAsync(IPAddress.Parse("10.168.197.66"), 14400);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = tcpClient.GetStream();
// Buffer to store the response bytes.
byte[] data = new byte[1024];
// String to store the response ASCII representation.
String responseData = String.Empty;
int count = 0;
while (true)
{
// Read the first batch of the TcpServer response bytes.
count = await stream.ReadAsync(data, 0, data.Length);
if (count > 0)
{
responseData = System.Text.Encoding.ASCII.GetString(data, 0, count);
//Dispaly responsed message
txtClientContent.Text = responseData;
}
}
It seems that this issue only occur if debugger is attached. For now this topic is closed.
I have searched a lot for this but could not find any specific answer that applies to my case. I have made device using GPS module and GSM/GPRS module with Arduino Mega 2560, and it sends me the location through SMS. Now I want to get the location parameters using GPRS. I have in mind to use TCP. I will send data through AT Commands from GPRS module, but I am confused on how to make a server on C#. I know that I would be needing a static/public IP for this. But I don't know how to get the public IP, and start receiving data which I send from GPRS module. Please please I need help because I am a beginner in Client/Server programming, and I am working on my final year project. Many thanks in advance!
please take a look at this TCP server and client example.
You will need a public static IP address. That is something you have to ask your broadband provider, and they will explain you the available options they have, probably you will have to pay extra money. You can use your current public IP address, that will be probably dynamic, but they don't use to change way to often, so whenever you are unable to connect, you will have to check if the IP changed or not, and set the new one.
This video series maybe a good introduction: https://vimeo.com/38103518
Here is the Server Code:
class Server
{
TcpListener server = null;
public Server(string ip, int port)
{
IPAddress localAddr = IPAddress.Parse(ip);
server = new TcpListener(localAddr, port);
server.Start();
StartListener();
}
public void StartListener()
{
try
{
while (true)
{
Console.WriteLine("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
t.Start(client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
}
public void HandleDeivce(Object obj)
{
TcpClient client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
string data = null;
Byte[] bytes = new Byte[256];
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);
if (data.StartsWith("##"))
{
data = "LOAD";
}
else
{
data = "ON";
}
byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("{1}: Sent: {0}", data, Thread.CurrentThread.ManagedThreadId);
}
client.Close();
}
}
A device is sending events every second, from 192.168.101.4 to 192.168.101.2:4002.
I need to listen and parse these events, but i fail already with the listening part.
Could someone please explain, how to do this with limited options of compact framework?
I solved it on my own, but thanks PaulH for the helpful tutorial.
For programmers with the same problem:
/// <param name="port">Port to use</param>
/// <param name="size">count of bytes to return</param>
/// <returns>a byteArray with received data</returns>
public static byte[] readEvent(int port, int size)
{
byte[] bytes = new byte[size];
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
TcpListener listener;
try
{
listener = new TcpListener(ipAddress, port);
listener.Start();
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream stream = tcpClient.GetStream();
stream.Read(bytes, 0, bytes.Length);
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return bytes;
}
In case of synchronous TCP server when ever a client connects i get a reference of Client example :
int serverPortNum = 9000;
socket while(true) {
ServerSocket connectionSocket = new ServerSocket(serverPortNum);
Socket dataSocket = connectionSocket.accept( );
// pass this reference(dataSocket ) to other part of program to read or write depending on app logic
}
Now i want to use asynchronous TCP Server using Netty so is there any way i can get the reference of ChannelPipeline or ChannelHandler created when a new client is connected.
On Client Side I can do it easily : sample code :
NioClientSocketChannelFactory ncscf = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
ClientBootstrap clientBootstrap = new ClientBootstrap(ncscf);
final DummyHandler dummy = new DummyHandler();
clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(dummy);
}
});
InetAddress inetaddress = InetAddress.getByName(host);
ChannelFuturecf=clientBootstrap.connect(newInetSocketAddress(inetaddress,port));
So every time i create a new client i have new DummyHandler reference
On Server Side : sample Code :
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new DummyServerHandler());
}
});
bootstrap.bind(new InetSocketAddress(port));
So when client request connection new DummyServerHandler object is created but i cannot get reference of this.
I may missunderstood the question but wouldn't this work.
Channel.getpipeline()