How can I convert a string to RemoteEndPoint ?
RemoteEndPoint is a property of a Socket, so you'd need to create a Socket first:
IPEndPoint ip = new IPEndPoint(address, port);
Socket mySocket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
So if you have a string something like "127.0.0.1:25", you need to grab the address and port components. Try myEndPointString.Split(":") to get the two components out.
Related
I have Thrift client-server application C# client and Python server. All in the same machine-Windows7. Debugging into the Thrift code I saw the client's socket cannot connect to the server's local server. BTW, The same C# client connects to C+ server and python and c++ clients connect to the same python server. Just C#-->Python combination fails.
The problem looks similar to Connecting Python SocketServer with C# Client. I tried to modify the code following the answer in the link above but still, C# socket throws "No connection could be made because the target machine actively refused it 127.0.0.1:9091"
Client(C#):
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Socket client = new Socket(ipAddress.AddressFamily,SocketType.Stream,
ProtocolType.Tcp);
TcpClient tcpClient = new TcpClient(AddressFamily.InterNetwork);
tcpClient.Client = client;
tcpClient.Connect(ip, port);
Why ipHostInfo.AddressList[1]? This selection takes IPv4 adapter from
ipconfig. I tries other indices as well. Server(Python, Inside
to Thrift-sever library):
res0 = socket.getaddrinfo(self.host,
self.port,
self._socket_family,
socket.SOCK_STREAM,
0,
socket.AI_PASSIVE |
socket.AI_ADDRCONFIG)
...
self.handle = socket.socket(res[0], res[1])
self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(self.handle, 'settimeout'):
self.handle.settimeout(None)
self.handle.bind(res[4])
self.handle.listen(self._backlog)
client, addr = self.handle.accept()
It never exits from accept in case of C# client
You have too much duplicate code. Try following :
//client
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(remoteEP);
//Server
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
TcpListener listener = new TcpListener(localEP);
listener.Start();
I need to create an instance of Socket class , But i am not sure what parameters should I parse to create TCP socket ,
System.Net .Sockets .Socket s = new System.Net.Sockets.Socket
(//what are the parameters required in here ?")
For tcp :
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
For Udp :
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
The above code example shows you have to instantiate a socket in either way
I have some client-server socket code that I want to be able to construct and (re)connect to periodically the same endpoint address: localhost:17999
Here is the server:
// Listen for a connection:
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 17999);
Socket listener = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Bind(localEndPoint);
listener.Listen(1);
// Accept the connection and send a message:
Socket handler = listener.Accept();
byte[] bytes = new byte[1024];
bytes = Encoding.ASCII.GetBytes("The Message...");
handler.Send(bytes);
// Clean up
handler.Shutdown(SocketShutdown.Both);
handler.Close();
handler.Dispose();
listener.Shutdown(SocketShutdown.Both);
listener.Close();
listener.Dispose();
And here is the client:
byte[] bytes = new byte[1024];
Socket receiver = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
receiver.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
receiver.Connect(new IPEndPoint(IPAddress.Loopback, 17999));
int num_bytes_received = receiver.Receive(bytes);
string result = Encoding.ASCII.GetString(bytes, 0, num_bytes_received);
receiver.Shutdown(SocketShutdown.Both);
receiver.Close();
receiver.Dispose();
When I create the client and server for the first time, it works fine. However when I create it again, I get an error:
"A request to send or receive data was disallowed because the socket is
not conne cted and (when sending on a datagram socket using a sendto
call) no address was supplied"
I would like to be able to spin up this mechanism arbitrarily whenever I need to with the following order of events:
Launch the server and wait to accept a connection
Launch the client and connect to the server
Accept the client connection at the server
Send a message to the client
Repeat when necessary
How can I do this?
Thx in Advance!
EDIT: Each time I build the client and server objects it is from a different process.
You have two issues:
1) You're closing the listener. Just leave it open.
2) You're setting ReuseAddress on the wrong socket and way too late. Set it on the listening socket before you call bind (since that's when you use the address).
Setting ReuseAddress on a socket you aren't going to bind doesn't do anything. You can remove that from the client.
I tried what Gene suggested and it seems to work:
// Listen for a connection:
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 17999);
using (Socket listener = new Socket(IPAddress.Loopback.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Bind(localEndPoint);
listener.Listen(1);
Thread t = new Thread(() =>
{
// Accept the connection and send a message:
using (Socket handler = listener.Accept())
{
byte[] bytes = new byte[1024];
bytes = Encoding.ASCII.GetBytes("The Message...");
handler.Send(bytes);
}
});
t.Start();
t.Join();
}
Thanks, all!
I am trying to fetch the IP address from the broadcast packets sent by a DSL modem and received on port 137 using UDP protocol. I am able to read the IP address when connectivity is present.
However, in unidentified network state, when my modem is configured for DHCP, and a specific range of IPs are allowed, and setting on my machine is auto-detect:
I get the default Local IP Address of the machine on reading the broadcast messages. That would be starting with 169.
Note: I am restarting the modem in order to receive the broadcast messages.
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 137);
sock.Bind(iep);
EndPoint ep = (EndPoint)iep;
int iLoopCount=0;
while (iLoopCount <= 10000)
{
Console.WriteLine("Ready to receiveā¦");
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.Default.GetString(data, 0, recv);
Console.WriteLine("{1}: from: {0}",((IPEndPoint)ep).Address.ToString(),DateTime.Now.ToString());
iLoopCount++;
// Console.WriteLine(sock.RemoteEndPoint.ToString());
}
sock.Close();
Console.Read();
Found the answer to my question at
http://www.codeproject.com/Articles/17031/A-Network-Sniffer-in-C
I created an application with server and client tool using sockets etc. When using my code on my computer works. Now I installed the Himachi software and I need to use this software in my application so that when a user connects with me, the application created could be used in this network. Note that this is my first time using sockets. The problem is that they are not connecting to each other and also it gives me this error on changing the ip and port: The requested address is not valid in its context
The send Tool
public Send(string Group, string port, string ttl, string rep, string data)
{
IPAddress ip;
try
{
Console.WriteLine("Send on Group: {0} Port: {1} TTL: {2}", Group,port,ttl);
ip = IPAddress.Parse(Group);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip));
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, int.Parse(ttl));
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Group),int.Parse(port));
Console.WriteLine("Connecting...");
s.Connect(ipep);
byte[] byData = System.Text.Encoding.ASCII.GetBytes(data);
s.Send(byData, SocketFlags.None);
Console.WriteLine("Closing Connection...");
s.Close();
}
catch(System.Exception e) { Console.Error.WriteLine(e.Message); }
}
The Receive tool
public string RecvData(string Group, string port)
{
string str = "";
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse(port));
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(Group);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip,IPAddress.Any));
// Getting the data
byte[] buffer = new byte[1024];
int iRx = s.Receive(buffer);
str = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
// Closing a Socket
s.Close();
return str;
}
Thanks
So your problem is that you are trying to use a VPN (hamachi) to connect two apps the server and the client so that the client can receive messages from the server right? I think that the error given "The requested address is not valid in its context" is because you are using a VPN but I don't know how this can be solved sorry. What I think is that maybe you might also need the network id and password but again I'm not sure. Please keep us informed because this is a very interesting question.